使用Javascript更改输入值 [英] Change input value with Javascript

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

问题描述

标题看似简单,但我需要帮助。

The title seems easy, but I need help.

我有一个字段输入email的表单,其值为null,直到用户填写为止。好的,点击提交按钮,我调用函数validate(),它是:

I have a form with a field input "email" of which value is null until the user fills it up. Okay, on click of the submit button, I call the function validate() which is:

function validate(){
    var email=document.getElementById("email");
    if(!(/[\w-\.]{3,15}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}/.test(email))) {
        email.setAttribute('value','Insert a correct email');
        email.style.border="2px solid red";
    } else {
        alert("Valid field"); // This is to test it works
        email.style.border="2px solid #63ce40";
        this.form.submit();
    }
    }

我想在这里做的是,如果是电子邮件插入不符合要求(无效),使用插入正确的电子邮件更改输入值。

What I want to do here is that if the email inserted does not meet the requirements (is not valid), change the value of the input with "Insert a correct email".

如果该字段为空,我单击提交,它工作得很好,但如果我插入文字并点击提交,唯一的变化将是获得2px红色边框的字段,但没有文字更改。

If the field is empty and I click submit, it works perfectly, but if I insert text and click submit, the only change will be the field getting a 2px red border, but no text change.

我想要要知道我必须这样做,当我点击提交错误的电子邮件时,将被删除并替换为插入正确的电子邮件文本。

I would like to know what I have to do so that when I click submit the wrong email that was written, is removed and replaced by the text "Insert a correct email".

输入是:

<li>
    <input type="text" id="email" name="email" 
    value="" onfocus="this.value=''" size="40"/>
</li>

我正在使用的提交按钮:

And the submit button I'm using:

<input id="bsubmit" type="button" value="Submit"
name="submit" onclick=";this.disabled=true;validate();
this.disabled=false;"/>

谢谢。

推荐答案

你尝试使用 setAttribute 是件好事,因为这是一个重要的方法,但问题是你不想修改 属性在这种情况下,它是DOM的一部分,但您想要修改< input> 元素的 属性

It's good that you were trying to use setAttribute at all because it's an important method, but the problem is that you don't want to modify the value attribute in this case, which is a part of the DOM, but you want to modify the <input> element's value property.

email.value = 'Insert a correct email';

http://jsfiddle.net/XJZwm/

这篇关于使用Javascript更改输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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