Search code examples
javascriptjqueryjquery-filter

Filter comma separated span text with jquery


I am using the jQuery .filter() function to check whether or not a particular value is selected in a checkbox list:

$("#Control").find("input[type=checkbox]:checked")
             .next("label")
             .filter(function () {
                return $.trim($(this).text()) == "Option 1"; 
             })
             .length != 0';

How can I accomplish this if I have a comma-separated list of values in a span and I want to check if a particular value is there or not?

ex. Home Phone, Email Address, Mobile Phone might be the span text


Solution

  • Split the text of the span on , and then check to see if your string is inside the resulting array:

    $("span").filter(function () {
                return $(this).text().split(/,\s*/).indexOf("Email Address") > -1; 
             });
    

    Example - http://jsfiddle.net/nFjCn/3/