开发者

Jquery Disable option in dropdown

Guys i have used the following code to disable an option using jQuery (jquery-1.4.2.min).The disable happens in Firefox , but not in IE.

<SELECT NAME="SCOPE" id="SCOPE">  
 <OPTION VALUE="G"> Global
 <OPTION VALUE="D"> Dynamic  
</SELECT>


 $("#SCOPE option[value='G']").attr("disabled","disabled");
 $("#SCOPE option[value='D']").attr("selected", "selected开发者_如何学JAVA");


I think i might be wrong but it could be because the select rather than option can be disabled. Since firefox is great and IE sucks, well you can guess why :) you having that problem. Use css to grey out the text of that option.

then on jquery do something like this.

$('#SCOPE').change(function(){
  if($('#SCOPE option[value="'+$(this).val()+'"]').attr('disabled') == 'disabled'){
    alert('Its disabled you cannot select this option');
  }
});

BTW. double check the code as I have not tested this :)


My take is bit different to other answers.

The aim is not to hide the options but just make them disable(to keep the UI consistent).

My Scenario :

I have multiple selects in a form and when an user selects an option in one of the selects the other selects should disable this option and vice versa. User is restricted from selecting the same option which is already selected. We normally disable the option but for IE 7 which does not support it. User also gets an option to add new selects.

Solution :

On load :

If the browser is IE7 then while populating the the selects and disabling the already selected options on other selects I am adding a custom attribute to the option("data-ie7-disabled") and also changing the color of the disabled options to '#cccccc'(which is the standard color for disabled options). This makes the UI look same across browsers.

On Change :

I save the previous option in a local variable(this is saved on focus).

When a user tries to change an option

User selects a complete new option which is not selected in any other dropdown. Then I loop through other selects and change the color and add custom attribute to this selected option on other selects.

When user selects an option that is already selected(The option which has grayed out color). I check if the option has this custom attribute on it first. If it has then > I simply revert the option to the previous one with an error message saying "This option is already selected or BLAH BLAH".

When user changes his existing option to a brand new option which is not selected in any other dropdown's. I again loop through all the other select options and remove the color on it and also the custom attribute.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜