Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traverse html table using jQuery

I am jQuery beginner trying to traverse an html table using jQuery. I went through various posts related to this but none could satisfy my problem statement.

So below is the sample html table:

<table>
    <tr>
        <td><input type="text" id="text1"></td>
        <td>
            <select>
                <option value="abc">ABC</option>
                <option value="def">DEF</option>
            </select>
        </td>
    <tr>
    <tr>..</tr>
</table>

I would ideally like to form a string with all the cell values of a record separated by a pipe like this: mytext,ABC | mytext2,DEF

Trying the following jQuery function but not been able to achieve this

$(function abc() {
    $("#save").click( function() {
        var dataList;
        var recordList; 
        var i = 0;
        $('#summaryTable tr').each(function() { 
            alert('tr found');
            $(this).find('td').each (function() {   
                alert('td found');
                var data =  $(this).html();
            });
        }); 
    });
});

Any help would be great.Thanks.

like image 573
sherry Avatar asked Dec 15 '25 16:12

sherry


1 Answers

[Edited]

according to your question and example, the trs have the same structure,

then what you need is something like this :

this is if you want "textfield value","selected value" | "next trs .." : JSFiddle

JS code:

var wordVal="";
var totalString = "";
$('#btn').click(function(){
    totalString="";
    $('table tr').each(function(i){
        $(this).children('td').each(function(j){
            if(j==0) wordVal = $(this).children('input').val().trim();
            else totalString+= wordVal+','+$(this).children('select').val()+'|';
        });
    });
    totalString= totalString.substring(0,totalString.length-1);
    console.log(totalString);
});

js code for ("textfield value"1,"option1" | "textField value"2,"option2" .. etc): JSFiddle

var wordVal="";
var totalString = "";
$('#btn').click(function(){
    totalString = "";
    $('table tr').each(function(i){
        $(this).children('td').each(function(j){
            if(j==0) wordVal = $(this).children('input').val().trim();
            $(this).children('select').children('option').each(function(k){
                totalString+= wordVal+(k+1)+','+$(this).html()+'|';
            });
        });
        totalString= totalString.substring(0,totalString.length-1)+'\n';
    });
    console.log(totalString);
});
like image 64
CME64 Avatar answered Dec 17 '25 05:12

CME64



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!