如何使用JavaScript函数将表单输入文本更改为大写 [英] How to change a form input text to uppercase using a JavaScript function

查看:108
本文介绍了如何使用JavaScript函数将表单输入文本更改为大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将表单输入字段(用户名)更改为大写,并删除文本中的所有空格。我知道有几种方法可以做到这一点,但我需要弄清楚如何使用函数来做到这一点。我需要通过它的id来获取输入,并使用toUpperCase方法,但我无法弄清楚这是否适合我的生活。正如你可能知道的那样,我是JavaScript新手。任何帮助将不胜感激。

HTML:

 < div class =登录形式> 
< h1 class =h1-login>欢迎< / h1>
< h4>请登入以享用我们的服务< / h4>

< form class =login-formname =login-formmethod =post>

< label for =username>< span class =required> *< / span>用户名:< / label>
< input id =usernametype =textname =usernameautofocus onkeyup =changeToUpperCase()>
< label for =password>< span class =required> *< / span>密码:< / label>
< input type =passwordname =passwordsize =8maxlength =8>

< input class =logintype =submitvalue =Login>

< / form>

< / div>

这里是JavaScript:

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

此代码无效...并且我不知道如何删除输入文本中的空格。请帮助我。

解决方案

我会将html更改为:

  onkeyup =changeToUpperCase(this)

(t){
var eleVal = document.getElementById(t.id)}将函数调整为这个

  function changeToUpperCase ; 
eleVal.value = eleVal.value.toUpperCase()。replace(/ / g,'');
}

示例


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.

解决方案

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

这篇关于如何使用JavaScript函数将表单输入文本更改为大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆