Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  85] [ 1]  / answers: 1 / hits: 50009  / 10 Years ago, tue, april 15, 2014, 12:00:00

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.



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>

More From » html

 Answers
27

You're on the right track.



Fiddle demo



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:



Fiddle demo



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;
}
}

[#71460] Sunday, April 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aidan

Total Points: 72
Total Questions: 95
Total Answers: 121

Location: Uzbekistan
Member since Sat, Feb 27, 2021
3 Years ago
aidan questions
Mon, Oct 11, 21, 00:00, 3 Years ago
Wed, Sep 29, 21, 00:00, 3 Years ago
Sun, Sep 5, 21, 00:00, 3 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;