Search code examples
javascriptjqueryhtmljquery-selectorsselected

jquery :selected always picks first element if none are selected


I have a select element

<select id='bill_to'>
     <option value='a634jhj2'>test@c.com</option>
     <option value='agfd4ghj2'>test2@c.com</option>
     <option value='asdf634jhj2'>tes3@c.com</option>
     <option value='agf2342d4ghj2'>test4@c.com</option>
</select>

If I do

  $('#bill_to').find(':selected') 

it returns the first option even though it is not selected.

If an option is selected

  $('#bill_to').find(':selected') 

works as expected and returns the correct option

What am I doing wrong? Is this a bug. This is driving me crazy. I just want it to return [] if there is nothing selected


Solution

  • If there are no select option with selected attribute, first option will be the selected option by default. You can try adding another option to top that contains default value as follow.

    <select id='bill_to'>
         <option value='-1'>Select<option>
         <option value='a634jhj2'>test@c.com<option>
         <option value='agfd4ghj2'>test2@c.com<option>
         <option value='asdf634jhj2'>tes3@c.com<option>
         <option value='agf2342d4ghj2'>test4@c.com<option>
    </select>
    

    If nothing is selected you will get -1 and then you can proceed.

    e.g. http://jsfiddle.net/fZv5t/