Reset/Un-select Select Option

不羁岁月 提交于 2019-12-20 05:02:35

问题


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?


回答1:


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/



来源:https://stackoverflow.com/questions/8496722/reset-un-select-select-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!