TheAnt. TheAnt. - 6 months ago 12
HTML Question

Make span element hidden when javascript validation succeeds

I am stuck on how to make a span element become hidden again when the javascript validation succeeds. Currently onchange and onblur a red span appears showing an error if there is no text or if there are numbers in a name field. This does not disappear when the correct text is put in. I was just wondering how to make this message disappear when the correct text is put in? Code is below.

Thanks,
Anthony

Javascript:

function validateName() {
var name = form.firstname.value;
if (form.firstname.value == "") {
document.getElementById("firstnameInvalid").style.visibility = "visible";
return false;
} if (/[0-9]/.test(name)) {
document.getElementById("firstnameInvalid").style.visibility = "visible";
return false;
}
return true;
}


Form HTML:

<form name="form" method="post" action= "userdetails.html" onsubmit="return validate(this)">

<p>First Name:<input type="text" name="firstname" onblur="validateName()" onchange="validateName()" id="name">
<span id="firstnameInvalid" style="color:red; visibility:hidden"> First Name is Invalid </span></p>

Answer

You're on the right track.

http://jsfiddle.net/isherwood/BHe5Z/

function validateName() {
    var name = form.firstname.value;

    if (form.firstname.value == "") {
        document.getElementById("firstnameInvalid").style.visibility = "visible";
        return false;
    } else if (/[0-9]/.test(name)) {
        document.getElementById("firstnameInvalid").style.visibility = "visible";
        return false;
    } else {
        document.getElementById("firstnameInvalid").style.visibility = "hidden";
    }
}

You can simplify this a bit by using your variable and removing the returns, which don't seem to be necessary:

http://jsfiddle.net/isherwood/BHe5Z/1/

function validateName() {
    var name = form.firstname.value;

    if (name == "") {
        document.getElementById("firstnameInvalid").style.visibility = "visible";
    } else if (/[0-9]/.test(name)) {
        document.getElementById("firstnameInvalid").style.visibility = "visible";
    } else {
        document.getElementById("firstnameInvalid").style.visibility = "hidden";
    }
}