1

// How to check if no option was explicitly selected in a select box? I use the following code and it works but is there a more elegant way to check if no option was explicitly selected in a select box without using 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');
    }

the form html is:  

    <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>  
4

1 回答 1

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

够优雅吗?

于 2012-06-28T09:55:04.540 回答