How to change a form input text to uppercase using a JavaScript function

耗尽温柔 提交于 2019-12-24 20:34:41

问题


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.


回答1:


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




回答2:


You can try this:

 onkeyup="changeToUpperCase(this)"

Then in the script:

function changeToUpperCase(el)
 {
     el.value =el.value.trim().toUpperCase();
 }



回答3:


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

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




回答4:


You could try using this:

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



回答5:


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.



来源:https://stackoverflow.com/questions/23172006/how-to-change-a-form-input-text-to-uppercase-using-a-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!