Search code examples
phpjqueryselectreset

Reset/Un-select Select Option


Usage:

I have a form that has a select drop-down that's controlled by another select drop-down. On loading the page (if values where selected before, PHP loads them) select drop-down #2 hides several options (this works). When selecting a particular option with select drop-down #1, select drop-down #2 hidden options become available (.show(), this works).

The problem: (An example to outline the problem: http://jsfiddle.net/RqhbY/7/)

When the hidden options are shown/available and one is selected and then the select drop-down #1 changes that value that hides the options in drop-down #2, On submission the selected hidden value gets submitted.

How can I un-select/reset the selected option that is now hidden?


Solution

  • http://jsfiddle.net/RqhbY/8/

    Try changing:

    $('select[name=two[0]] option').attr('selected', false);
    

    with:

    $('select[name=two[0]] option').removeAttr('selected');
    

    UPDATE

    OK, I tested the above code in IE 8 and the disabled <option> is still selected. This seemed to work however:

    $('select[name=two[0]]').children('option').removeAttr('selected').filter(':nth-child(1)').attr('selected', true);
    

    Demo: http://jsfiddle.net/RqhbY/9/

    Note that you may want to update the .filter() call to only select non-disabled options but I'll leave that for you.

    UPDATE

    If you call .attr('selectedIndex', -1) on the <select> element then you can have no <option>s selected. The drop-down will not show a value but instead will be blank.

    Demo: http://jsfiddle.net/RqhbY/10/