简体   繁体   中英

finding a specific td and assign the value to a text input using jquery

So I am trying to iterate through a table and find specific text in td and assign it to a variable. This is what I have so far:

 var table = $(this).closest('table');

    $("td",table).each(function(){
        if($(this)+':contains("AD Login")') console.log($(this).next().text());
    });

However this code prints all the cells to the console, instead of the sibling of the found cell

Use the .is() function with the :contains selector ( jQuery version added: 1.1.4 ).

$("td",table).each(function(){
    if($(this).is(":contains('AD Login')")) console.log($(this).next().text());
});
  • Notice that .contains() doesn't fit here for it can only check to see if a DOM element is a descendant of another DOM element. (From the API).

Regarding what you've written in your comment - it always returns true because you're just concatenating $(this) 's string value to another string (":contains etc."). When converted to boolean type, string immediates are always true.

jQuery has a contains selector http://api.jquery.com/contains-selector .

Example :

var table = $(this).closest('table');

table.find('td:contains("AD Login")').each(function(){
    console.log($(this).next().text());
});

Assuming an 'older' version of jQuery (from comments to another answer):

$("td",table).each(function(i,el){
    if ((el.textContent || el.innerText) == 'AD Login') {
        console.log($(this).next().text());
    }
});

The above will test that the text of the td is exactly equal to the string ('AD Login'), to check if that text is simply present within the text of the td :

$("td",table).each(function(i,el){
    if ((el.textContent || el.innerText).indexOf('AD Login') > -1) {
        console.log($(this).next().text());
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM