Reputation: 197
I am using the following javascript code to check for nothing being entered in a form and it is not working. Can anyone suggest a reason?
function validateForm()
{
var a=document.getElementById("quiz_01").value;
$question = a;
if (a=="" || a==null) {
alert("Question 201 must be filled out");
form1.quiz_01.focus();
return false;
}
}
An extract of the html is as follows:
<form id="form1" name="form1" method="post" action="" onsubmit="return validateForm()">
<table class="table">
<tr>
<td>
<label for="quiz_01">201 A one followed by 100 zeros is a Googol</label>
</td>
<td>
<select name="quiz_01" id="quiz_01">
<option value=" "> </option>
<option value="100">100</option>
<option value="90">90</option>
<option value="80">80</option>
<option value="70">70</option>
<option value="60">60</option>
<option value="50">50</option>
<option value="40">40</option>
<option value="30">30</option>
<option value="20">20</option>
<option value="10">10</option>
<option value="0">0</option>
</select>
</td>
</tr>
</table>
<p>
<input type="submit" name="next" value="Next >">
</p>
Upvotes: 0
Views: 8625
Reputation: 3972
You could not access the value directly when working with an <select> element. use following:
var element = document.getElementById("quiz_01");
var a = element.options[element.selecedIndex];
EDIT: (credits to nnnnnn)
In modern browsers the direct access will work, but if you're targeting an old Version (I think especially of Internet Explorer ;) ) the showed approach will gain you compatibility.
Upvotes: 0
Reputation: 368
change the code to
var e = document.getElementById("quiz_01");
var ev = e.options[e.selectedIndex].text;
if(ev===' '){
alert('question 201 is a required field');
}
you should use === not == whwn comparing strings
Upvotes: 0
Reputation: 56501
Trim the whitespaces.
var a=document.getElementById("quiz_01").value.trim();
Upvotes: 1
Reputation: 150010
The first option:
<option value=" "> </option>
Has a value that is a single space, not an empty string. So either change the value
or change the JS code. Note also that the .value
property will never be null
so you don't need to test for that.
if (a == " ") {
Demo: http://jsfiddle.net/RyN5W/
Upvotes: 2