验证javascript中的选择选项

时间:2013-03-07 20:47:16

标签: javascript

我通过Struts HTML标签为特定的jsp使用select选项。选项的值为Yes和No.这是代码。

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

默认情况下,选择选项列表中显示的值为YES。 我正在执行验证,如果没有选择任何值(作为'YES'上给出的Selected属性)并且提交了表单,则应该抛出警报以选择新值。以下是我的代码。

 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;
 }

以上代码未正确验证。任何人都可以建议我一些变化。 谢谢

1 个答案:

答案 0 :(得分:1)

这是如何检查所选值是否为默认值,即使我不太了解你的意图。

el = document.getElementById('choice');

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

PS:您可能需要修复代码:

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