开发者

JQuery :contains function limit to exact match

开发者 https://www.devze.com 2023-02-21 06:15 出处:网络
Using the JQuery :contains function to decide which option on a select is selected from a SESSION variable.

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

The contains function is matc开发者_如何学运维hing 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');


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

$('option').filter(function(){
    return $(this).html() == "<?php echo $_SESSION['divelevel'];?>";
}).attr('selected', 'selected');


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.


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');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号