Henioryb
Henioryb

Reputation: 11

jQuery how to check td value and compare it to array

I have an array

arr = ["value1", "value2", "value3"];

and I want to check td value if it contains a value from my array. If yes, I would like to set a value of another td

I try this, but doesn't work:

   <table>
     <tr>
      <td class="woj">value1</td>
      <td class="user"></td>
     </tr>

     <tr>
      <td class="woj">value5</td>
      <td class="user"></td>
     </tr>

     <tr>
      <td class="woj">value6</td>
      <td class="user"></td>
     </tr>
    </table>

var arr = ["value1", "value2", "value3"];     
var woj = $('.woj').html();
if($.inArray(woj, arr) > -1) {         
    $(".user").text("user1");
 }

Upvotes: 0

Views: 395

Answers (2)

mikus
mikus

Reputation: 3215

It's because there are many elements matching your selector '.woj'.

Try to iterate through all of them and check each of them separately. Also its better to use innerText property instead of the html method. More or less

$.each($('.woj'), function(idx, td){
    if($.inArray(td.innerText, arr) ....
});

In general, such thinga are easier if you introduce a framework, like knockout. Then you operate on data model, not on the presentation layer and parsing DOM.

Upvotes: 0

dfsq
dfsq

Reputation: 193261

You will need to iteration over all .woj elements and in case inner text in the array, modify next table cell content:

var arr = ["value1", "value2", "value3"];     

$('.woj').each(function(i) {
    if (arr.indexOf($(this).text().trim()) > -1) {         
        $(this).next().text("user" + i);
    }
});

Upvotes: 1

Related Questions