JQuery: contains function constraint for exact match

Using jQuery: Contains a function to determine which option in a selection item is selected from the SESSION variable.

The contains function corresponds to the wrong parameter, as their version is "PADI Open Water" and another "PADI Open Diving Instructor"

How do we limit its relevance to exact content and no more?

$('option:contains("<?php echo $_SESSION['divelevel'];?>")').attr('selected', 'selected'); 
+7
source share
3 answers

Try using .filter() to find the option you need.

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

Answer Rocket Hazmat was able to help me in my current project where the cookie value is set, and the row of the table for which this cookie value should be set should be highlighted. The code I originally had was:

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

That worked fine until we realized that the table cell might contain the value of activeRowCookie plus other characters, but we need an exact match with all the contents of the cell. In addition, we look for a cell that contains this exact value and no more, but then we select the row in which the cell is located, and not just the cell itself. So I got it to work, adapting the answer here to the following:

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

And yes, this initial selector really needs to be like that, because we don’t want it to look at the cells in the THEAD element.

0
source

Try adding a pseudo-random 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
source

All Articles