检查在不使用jquery的情况下在选择框中没有明确选择任何选项?

时间:2012-06-28 08:44:26

标签: javascript

//如何检查选择框中是否未明确选择任何选项? 我使用以下代码,它的工作原理 但有没有更优雅的方法来检查是否在没有使用jquery的情况下在选择框中没有明确选择任何选项?

    // This function is called onclick or onchange a select in the submitting form
    function getplano(aaaooo){
     var esepen = document.getElementById('esEpendysi');
     var exepen=document.getElementById('exEpendysi');
    // (esEpendysi and  exEpendysi are two other selects in the submitting form)
     try{
     var esepval = esepen.options[esepen.selectedIndex].innerHTML;
    // or  ////~ var esepval = esepen.options[esepen.selectedIndex].text;   
    }
    catch(e){
    // alert(e.name + "\n" + e.message)
     //When there is not a selected value the error thrown is:
     // NS_ERROR_DOM_INDEX_SIZE_ERR
    //Index or size is negative or greater than the allowed amount
    }
    try{
      var exepval = exepen.options[exepen.selectedIndex].innerHTML; 
    }
    catch(e){
    // alert(e.name + "\n" + e.message)
    }
    if(esepval && exepval) {
    alert(aaaooo +'&esepen='+esepval+'&exepen='+exepval);
//example: handling.php?tzapan=panel&esepen=aluminium&exepen=wood
    }
     else
        alert('Please select Outside or/and Inside surface finish');
    }

表格html是:                                    

    <BODY >
    <form name="" action="" method="post">
    <table >
    <tr><td align=left>Outside finish:<br><SELECT size='2'  name=exEpendysi  id='exEpendysi'  ><OPTION>aluminium</OPTION><OPTION>wood</OPTION></SELECT></td><td align=left>Interior finish:<br><SELECT size='2'  name=esEpendysi  id='esEpendysi' ><OPTION>aluminium</OPTION><OPTION>wood</OPTION></SELECT></td></tr>
    <tr><td style='font-size:16px;font-weight:bold;'>fixed side<br><select  size='2' id='selectplainou' name='selectplainou' onChange="getplano('handling.php?tzapan='+this.options[this.selectedIndex].innerHTML)" > <OPTION>panel</OPTION><OPTION>glass</OPTION> </select ></td>
    <td><input type="submit" value="Submit" /></td></tr>
    </table>
    </form>
    </BODY></HTML>  

1 个答案:

答案 0 :(得分:0)

function getplano( aaaooo ) {
    var esepen = document.getElementById( 'esEpendysi' );
    var exepen = document.getElementById( 'exEpendysi' );

    // These two will return true if it's the default value
    // Else, it returns false.
    var esepenSelected = esepen.options[ esepen.selectedIndex ].value === "default option";
    var exepenSelected = exepen.options[ exepen.selectedIndex ].value === "default option";

    // Since we have these two variables, we can elegantly use:
    if ( !esepenSelected && !exepenSelected ) {
        // do something
    }
}

那够优雅吗?