0

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

2
  • 1
    I don't understand what you're trying to achieve, when the form is submitted you're always going to ask the user to choose the other value, reguardless of what they have selected. Commented Mar 7, 2013 at 20:52
  • I like to validate the user input in such a way that if the user selects the same value without changing the value(without selecting other value) a error should be thrown. I am unable to do the validation. could you please help me out. Commented Mar 7, 2013 at 21:01

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.