atamata
atamata

Reputation: 1077

jQuery disable dropdownlist item by text

I have a asp:net dropdownlist which has extra items appended server side:

<asp:DropDownList ID="ddlResult" runat="server">
    <asp:ListItem Value="" Text="-- Please Select --"></asp:ListItem>
</asp:DropDownList>

...and basically I would like to disable/enable an entry by the display text in jQuery. I've tried the numerous examples on here but none of them seem to work for me. eg.

$("#ddlResult option[text='Positive']").attr('disabled','disabled');

..or...

$("#ddlResult option[text='Positive']").hide();

...or ...

$("#<% =ddlResult.ClientID %> > option[text='Positive']").attr("disabled", "disabled")

...amongst others.

Can anyone advise where I am going wrong?

Thanks in advance.

Upvotes: 0

Views: 2866

Answers (3)

Ali Sadri
Ali Sadri

Reputation: 1676

try bellow pattern

$(document).ready(function() {

$("#<%=DropdownListId.ClientId%> option[value='1']").attr("disabled","disabled");

});

Upvotes: 0

Dennis R
Dennis R

Reputation: 3237

May be something like this. You can use the :contains selector to find the text and disable the option.

$('#ddlResult option:contains("Positive")').prop("disabled", true);

or

$('#ddlResult option:contains("Positive")').attr("disabled", "disabled");

Working Demo

Upvotes: 3

PeterKA
PeterKA

Reputation: 24638

You would have to use the filter method to select the correct option element and then hide or disable as follows:

 $("#ddlResult option").filter(function() { 
      return $(this).text().trim() == 'Positive'; 
 }).hide();

 $("#ddlResult option").filter(function() { 
      return $(this).text().trim() == 'Positive'; 
 }).prop('disabled',true);

Please note that to toggle between enabled and disabled you would have to use .prop() -- recommended:

1. .prop('disabled',false); //to enable
2. .prop('disabled',true); //to disable

If you choose to use .attr('disabled', '..anything..') to disable, you have to use .removeAttr('disabled') to enable.

Upvotes: 2

Related Questions