Happydevdays
Happydevdays

Reputation: 2072

how to loop through rows in an HTML table to find a specific value?

I have the following sample html: https://jsfiddle.net/pgd8e46b/1/

What I'm trying to do is let the users click on a row from the "available_widgets" table and if it's not already in the "existing_widgets" table, add it and do other things.

I have the logic to grab the appropriate table and start the loop...

 var check_for_duplicates = function (row_id) {     
     var table = document.getElementById('existing_widgets');
     var rows = table.getElementsByTagName('td');
     for (var i = 0, len = rows.length; i < len; i++) {
         console.log(i);

     }
     console.log(rows);
     return true;
 }

but I don't know how to compare the ID field with the id that's passed in. I still have to write the logic that strips out the "row_" prefix from the id that's passed to the check_for_duplicates() method.

Any suggestions would be appreciated.

Upvotes: 1

Views: 206

Answers (3)

mike.k
mike.k

Reputation: 3437

This is a working function in JS. I would also suggest using some other prefix on the existing_widgets table, perhaps existing_row_#, and then you'd just need to modify the replace() component.

function check_for_duplicates(row_id) {
    var table = document.getElementById('existing_widgets');
    if (document.getElementById(row_id.replace('row_', ''))) {
        console.log(row_id + ' is a duplicate');
        return true;
    }  else {
        console.log(row_id + ' is not a duplicate');
        return false;
    }
 }

Upvotes: 0

dfsq
dfsq

Reputation: 193261

You can simplify check_for_duplicates function if you use jQuery to find widget row by id:

$('#available_widgets').on('click', 'tr', function () {
    if (check_for_duplicates(this.id)) {
        return false;
    } else {
        alert('otherwise, do other stuff');
    }
});

var check_for_duplicates = function (row_id) {
    return !!$('#existing_widgets').find('#' + row_id.replace('row_', '')).length;
}

Upvotes: 0

lucky7id
lucky7id

Reputation: 385

I think what you are looking for is the id property in the returned elements.

rows[i].id should give you what you are looking for in your loop.

to strip off the prefix: rows[i].id.replace('row_', '') That will create a new string for you to compare against.

Upvotes: 1

Related Questions