JQuery :contains function limit to exact match

2019-01-20 09:18发布

Using the JQuery :contains function to decide which option on a select is selected from a SESSION variable.

The contains function is matching the wrong option as their is an option 'PADI Open Water' and another 'PADI Open Water Scuba Instructor'

How do we limit it to match the exact content and no more?

$('option:contains("<?php echo $_SESSION['divelevel'];?>")').attr('selected', 'selected');

3条回答
聊天终结者
2楼-- · 2019-01-20 09:59

Try add a extend pseudo function:

$.expr[':'].textEquals = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().match("^" + arg + "$");
    };
});

Then you can do:

$('p:textEquals("<?php echo $_SESSION['divelevel'];?>")').attr('selected', 'selected');
查看更多
一夜七次
3楼-- · 2019-01-20 10:11

Rocket Hazmat's answer was able to help me on my current project, where a cookie value is set and the table row that that cookie value pertains to needs to be highlighted. The code I originally had was:

$(".datalist TBODY TR:has('TD.itemId:contains(" + activeRowCookie + ")')").attr('id', 'activeRow');

Which worked fine until we realized that a table cell could contain the activeRowCookie value plus other characters, but we needed an exact match to the entire contents of the cell. Also, we are looking for the cell that contains that exact value and no more but then we highlight the row that cell is in, not just the cell itself. So I got it to work by adapting the answer here to the following:

$('.datalist TBODY TR TD.itemId').filter(function () {
  return $(this).text() == activeRowCookie;
}).parent().attr('id', 'activeRow');

And, yes, that initial selector does need to be like that because we don't want it looking at cells in the THEAD element.

查看更多
Fickle 薄情
4楼-- · 2019-01-20 10:18

Try using .filter(), to find the option you want.

$('option').filter(function(){
    return $(this).html() == "<?php echo $_SESSION['divelevel'];?>";
}).attr('selected', 'selected');
查看更多
登录 后发表回答