views:

9

answers:

1

I know this should be easier if I could only use optgroups. But I am trying to avoid hacking core of my CMS, so jQuery should come to rescue again, hopefully.

I have a select with options in a hierarchy sometimes, and I want to put attributes disabled to any of options containing text NOT starting with a dash. I want to code like:

Set disabled attributes to selectors with options text NOT starting with a dash ("-").

<select id="options">
<option value="" selected="selected">- Please choose -</option>
<option value="1">Parent1</option>
<option value="2">-child1</option>
<option value="3">-child2</option>
<option value="4">-child3</option>
<option value="5">-child4</option>
<option value="6">Parent2</option>
<option value="7">-child5</option>
<option value="8">-child6</option>
<option value="9">-child7</option>
<option value="10">-child8</option>
</select>

The closest solution is here http://stackoverflow.com/questions/2012299/contain-start-by,

$.extend($.expr[':'], {
    startsWith: function(elem,match) {  
        return (elem.textContent || elem.innerText || "").indexOf(match[3]) == 0;
    }  
});

But I can't seem to do it right this far.

Any help would be very much appreciated. Thank you very much.

+1  A: 

You can use .filter(), like this:

​$("#options option").filter(function() {
    return $(this).text().indexOf("-") !== 0;
}​).attr('disabled', true);​​

This filters out any elements that don't have text starting with "-", you can see a demo here.

The custom selector approach, like your question, would be this:

$.extend($.expr[':'], {
    startsWith: function(a, b, match) {
        return $(a).text().indexOf(match[3]) === 0;
    }  
});

$("#options option:not(:startsWith(-))").attr('disabled', true);​

You can see a demo of that method here.

Nick Craver
You are my hero, Nick. Works like a charm. This should also help lots of CMS users with this limitation who may be lucky to find this. Thank you ever so much.
swan
BTW, for learning purposes, Can I put .attr('disabled', 'disabled');​​ there as well instead? Thanks
swan
With the second option, I was almost there save for the part of ":not(:" about which I was confused with ".not". Thanks
swan
@kuswantin - It's better to use `.attr('disabled', bool)` and `.attr('readonly', bool)` in this case, since jQuery actually operates on the DOM. `disabled="disabled"` just sets true because `"disabled" !== false`, it weak type converts to true.
Nick Craver
Yes, thanks. Wish I had clear understanding of this great software from head to toes :) But I am glad that I am always lucky to find help like you. Thanks
swan