Question

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
Was it helpful?

Solution 2

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.

OTHER TIPS

There is no need to add a default first option... Just use .prop() and change the selectedIndex:

$('#qwe').prop('selectedIndex', -1); 

DEMO: http://jsfiddle.net/dirtyd77/j76yH/2/

Let me know if you have any questions!

How about this?

    <select id="demo">
      <option value="-1">---</option>
      <option value="1">1</option>
      <option value="2">1</option>
    </select>

As hexblot said, every selectbox has a selected value. Always.. ;)

Try with the following statement:

if ($('#qwe option[selected="selected"]').val() === undefined) return -1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top