views:

268

answers:

6

I have a jQuery reference to a HTML select list. I need to iterate the options and check to see if the text of the option matches a regex, if it does I want to add a cssclass to the option. How do I do this?

var ddl = $($get('<%= someddl.ClientID %>'));

Can I take advantage of the .each() function somehow?

Example

<select id="someddl">
<option value="21">[21] SomeData ***DATA***</option>
<option value="22">[22] SomeData ***DATA***</option>
<option value="23">[23] SomeData </option>
<option value="24">[24] SomeData </option>
<option value="25">[25] SomeData ***DATA***</option>
 </select>

I want to add a CSS class to items 1, 2, 5 in this sample. In c# my regex was Regex expression = new Regex(@"\*\*\*"); but I want to do this through javascript now, so it's likely the regex will look a bit different.

Any ideas what I can do here to accomplish the requirement?

Thanks, ~ck

+1  A: 

Well, of course you can take advantage of $.each(), somehow like that:

$("#someddl option").each(function(i){
    var val = $(this).html();

    if(// regex)
    {
     $(this).addClass("myclass");
    }
});

You'll have to do the regex yourself, since it pretty much pain in the arse :P

usoban
A: 

Something like this should work:

$('select[id=whatever] option').each(function() { 
  if (... your condition ...) {
    $(this).addclass('cssClass');
  }
});
John Fisher
Why would you use $('select[id=whatever] option') when you could use $('#idofselect option')?
T B
In my experience, it's normally faster to use the tag than to simply search by [id=whatever]. If you're using '#whatever', then that may be a different story. I normally search by 'tag.class', so this was the most obvious solution to me.
John Fisher
A: 

I'd do it like this

$(function()
{
  $("#someddl option").each(function(i,elem)
  {
    if( /\*{3}/.test( elem.text) )
    {
        $(elem).addClass("myclass");
    }
  });
} );

Just know that there's a very limited subset of CSS that you can actually apply to <option> elements

Peter Bailey
A: 

The re you are looking for is:

re = /[\*]{3}[^\*]{1,}[\*]{3}/

/[\*]{3}/ // match 3 *
/[^\*]{1,}/ // match atleast 1 non *
googletorp
+1  A: 

As I wrote in my answer to your C# question, you do not need Regex if you want to match 3 asteriks. Try following:

$(document).ready(
function()
{
    $('#someddl option:contains("***")').addClass('selected');
}
);
SolutionYogi
A: 

If you have the regexp, there is a post explaining how to extend jquery to use regexp.

http://blog.mastykarz.nl/jquery-regex-filter/

jQuery.extend(
    jQuery.expr[':'], {
        regex: function(a, i, m, r) {
            var r = new RegExp(m[3], 'i');
            return r.test(jQuery(a).text());
        }
    }
);

This would allow you to use the regexp right in the selector instead of looping through the selected results and match a regular expression.

MacAnthony