質問

I'm trying to change a form input field (username) to uppercase and to remove all spaces within the text. I know there are a few ways one could do this but I need to figure out how to do this using a function. I need to get the input by it's id and use the toUpperCase method but I cannot figure this out for the life of me. As you might be able to tell, I am new to JavaScript. Any help would be greatly appreciated. Thank you.

HTML:

<div class="login-form">
                <h1 class="h1-login">Welcome</h1>
                <h4>Please login to enjoy our services</h4>

                <form class="login-form" name="login-form" method="post">

                    <label for="username"><span class="required">*</span>Username:</label>
                        <input id="username" type="text" name="username" autofocus onkeyup="changeToUpperCase()">
                    <label for="password"><span class="required">*</span>Password:</label>
                        <input type="password" name="password" size="8" maxlength="8">

                    <input class="login" type="submit" value="Login">

                </form>

            </div>  

Here is the JavaScript:

function changeToUpperCase() {
document.login-form.value = document.login-form.value.toUpperCase();
}

This code does not work... and I have no idea how to remove spaces from an input text. Please help me.

役に立ちましたか?

解決 2

I'd change the html to this:

onkeyup="changeToUpperCase(this)"

And adjust the function to this

function changeToUpperCase(t) {
   var eleVal = document.getElementById(t.id);
   eleVal.value= eleVal.value.toUpperCase().replace(/ /g,'');
}

Example

他のヒント

You can try this:

 onkeyup="changeToUpperCase(this)"

Then in the script:

function changeToUpperCase(el)
 {
     el.value =el.value.trim().toUpperCase();
 }
function changeToUpperCase() {
    document.getElementById("username").value = document.getElementById("username").value.toUpperCase().replace(" ", "")
}

Example here: http://jsfiddle.net/haxtbh/DDrCc/

You could try using this:

('text with spaces').replace(" ", "");

Something like this:

function trimAndUpper(id){
    var element = document.getElementById(id);
    element.value= element.value.trim().toUpperCase();
}

Add the trim function to a String:

String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, '');
  };

Usage: FIDDLE

BTW using str.Replace isn't good. This will replace the first occurance only.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top