Search code examples
javascriptjqueryselectselectedindex

Return SelectedIndex From Select Element


Is it possible to that have the selectedIndex return -1 if nothing is selected, rather than the element-text at position 0.

Also the selectedIndex returns 0 even if nothing is selected.

<select id="qwe" name="qwe">
    <option>11</option>
    <option>22</option>
</select>   

document.someForm.qwe.value
//returns 11

$('#qwe option:selected').val()
//returns 11



<select id="qwe" name="qwe">
    <option selected="false">11</option>
    <option>22</option>
</select>   
$('#qwe option:selected').val()
//returns 11

<select id="qwe" name="qwe">
    <option selected="false">11</option>
    <option selected="false">22</option>
</select>   
$('#qwe option:selected').val()
//returns 22

Solution

  • Select boxes must always have a value selected (by default the first option). If you want such a behavior, just add an empty option to the top of your list, with whatever value ( eg -1 ) you want.