Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  135] [ 7]  / answers: 1 / hits: 16091  / 12 Years ago, mon, august 13, 2012, 12:00:00
<!DOCTYPE html>

<html>
<head>
<meta charset=utf-8>
<title>Javascript Form Testing</title>
</head>

<body>
Name: <input type=text name=Name value=Name id=fname> <br>
Email: <input type=text name=Email value=Email id=mail > <br>
Phone: <input type=text name=Number value=Phone Number id=dvr onchange=validatePhone();>
<span id=phoneval> ?</span>

<script type=text/javascript>
phonenum = document.getElementById(dvr).value.length;
function validatePhone() {
if (phonenum == 10){
document.getElementById('phoneval').innerhtml=<-- Valid;
}
else{
document.getElementById('phoneval').innerhtml=<-- Not Valid;
}
}
</script>
</body>
</html>


Hi, I was getting the error 'Uncaught TypeError: Cannot read property 'value' of null' when the tag was in the head, but since I moved it, it went away. However, now it outputs no error and does NOTHING. Please help?



Sorry for any formatting and things, new :/


More From » html

 Answers
10

Edit:



Slightly different implementation that works: http://jsfiddle.net/SfTR2/ Make sure the JS is loaded after the HTML, or use window.onload



Original answer:



You need to get the length within the validation function:



   function validatePhone() {
var phonenum = document.getElementById(dvr).value.length; //MOVE IT HERE
if (phonenum == 10){
document.getElementById('phoneval').innerHTML=<-- Valid;
}
else{
document.getElementById('phoneval').innerHTML=<-- Not Valid;
}
}


As previously you were caching the empty length.



Also, as @su mentioned, you need to use innerHTML


[#83680] Friday, August 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
allans

Total Points: 336
Total Questions: 120
Total Answers: 119

Location: Peru
Member since Mon, Jun 6, 2022
2 Years ago
allans questions
;