Forum Moderators: open
getting an error when trying to validate a drop down menu. the error is 'document.feedbackform.country.selectedIndex' is null or not an object.
This is part of the script:
if ( document.feedbackform.country.selectedIndex == 0 )
{
alert ( "Please select your country." );
valid = false;
}
Would greatly appreciate your help.
Just a little addition to make your code more portable, you don't need to reference the form field with the full dot syntax, just pass the objects. If you check this out, note that it will work for your country drop-downs as well as a state or any other required DD.
<script language="javascript">
function check(form) {
var obj,msg;
msg = '';
var requireds = new Array('name','email','state','country');
for (i=0;i<requireds.length;i++) {
obj=eval('form.'+requireds[i]);
if ((obj.type=='select-one') && (obj.selectedIndex==0)) {
msg = 'Please select your '+ requireds[i];
}
else if (obj.value == '') {
msg = 'Please enter your ' + requireds[i];
}
if (msg!='') { break; }
}
if (msg!= '') { alert(msg); }
else { form.submit(); }
}
</script>
<form onSubmit="return false">
Name <input type="text" name="name" value="1"> <br>
Email <input type="text" name="email" value="1"> <br>
Country <select name="country">
<option value="">select</option>
<option value="Afghanistan">Afghanistan</option>
</select> <br>
State <select name="state">
<option value="">select</option>
<option value="Afghanistan">Afghanistan</option>
</select> <br>
<input type="submit" onClick="check(this.form);" value="go">
</form>
Your error message
'document.feedbackform.country.selectedIndex' is null or not an object.
Means that Javascript is not recognizing that string as an object in the page. This can be for one of many reasons - like I said, an error in the page code somewhere else may cause it as well as an outright typo. So first, use one of the online or offline HTML validators to make sure your page doesn't have an error in it. One misplaced quotemark can ruin your day.
Here, temporarily add this snippet to your validation routine. What this does is it iterates through the entire form and pops an alert for each form object. Watch for the country object, make sure it's being recognized. It's a little annoying but helps you find your problem areas.
for (i=0;i<document.feedbackform.length;i++) {
var obj = document.feedbackform.elements[i];
alert('Field name: ' + obj.name + ' type: ' + obj.type);
}