niks
niks

Reputation: 1083

validation of select option in javascript

i am using select option through Struts HTML tags for a particular jsp. The values of the option are Yes and No. Here is the code.

  <select name="select" id='choice'>
     <option value="<%YES%>" selected><%="YES"%></option>
     <option value="<%=NO%>"></option>  

The value seen in the select option list by default will be YES. I am performing validation such that if no value is selected(as Selected property given on 'YES') and form is submitted, a alert should be thrown to select new value. Below is my code.

 if( document.form.select.value == "YES" )
 {
   alert( "Please select other value" );
   return false;
 }
 if( document.form.select.value == "NO" )
 {
   alert( "Please select other value" );
   return false;
 }

The above code is not validating properly. Can anyone suggest me some changes. Thanks

Upvotes: 0

Views: 10265

Answers (1)

Mehdi Karamosly
Mehdi Karamosly

Reputation: 5428

This is how to check if the selected value is the default value, even though I am not understanding very well your intentions.

el = document.getElementById('choice');

if( el.options[el.selectedIndex].defaultSelected){
    alert("Please select other value");
    return false;
}

PS: you probably need to fix your code :

<select name="select" id='choice'>
     <option value="<%=YES%>" selected><%="YES"%></option>
     <option value="<%=NO%>"></option>
</select>

Upvotes: 1

Related Questions