Change input value with Javascript

2019-02-25 08:28发布

问题:

The title seems easy, but I need help.

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".

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".

The input is:

<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;"/>

Thank you.

回答1:

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/



回答2:

Try this email.value = 'Insert a correct email'; instead of email.setAttribute('value','Insert a correct email');