jQuery loop through table and get element

2019-09-16 00:58发布

问题:

i've got some form input elements in an html table like this:

<table>
    <thead>
    ....
    </thead>
    <tr>
        <td><input type="text" name="n_time" id="5030c9261eca0" value="2012" /></td>
        <td><input type="text" name="n_name" id="5030c9261eca0" value="a name" /></td>
        <td><textarea name="n_comment" id="5030c9261eca0">bla</textarea></td>
    </tr>
</table>

now, i need to send this form data using $.post to my PHP processing page which looks something like

if($_POST['data']){
    $array = json_decode($_POST['data']);

}

so i need to get all my form elements and somehow made then into JSON

and this is what i did:

// assume i can get 5030c9261eca0 from my predefined vars...
$my_array = $("#5030c9261eca0").map(function () { return $(this).is("input")?$(this).val():$(this).text(); } );
//now convert
JSON.stringify($my_array);
// the conversion failed with : Uncaught TypeError: Converting circular structure to JSON 

this error poped up:

Uncaught TypeError: Converting circular structure to JSON 

how do i fix this?

also, if i do regluar HTTP post via HTML forms, i can recieve form data like $_POST['n_name'] in PHP if i have a HTML form element with attribute n_name, how can i accomplish the same with the above?

回答1:

First loop through all tr, then loop trought all input,textarea and push gathered values to array.

var data = [];      
$('table tr').each(function(){
    var row = {};
    $(this).find('input,textarea').each(function(){
        row[$(this).attr('name')] = $(this).val();
    });
    data.push(row);
});

// now you can use "data" :)

Example data:

[0][n_time] = foo
[0][n_name] = bar
[0][n_comment] = 123
[1][n_time] = foo
[1][n_name] = bar
[1][n_comment] = 123
...

jQuery:

$.post("test.php", { 'mydata': data } );

PHP:

foreach($_POST['mydata'] as $row) {
    echo $row['n_name'];
}

It's good idea to convert it to jQuery function:

(function( $ ) {
  $.fn.tableData = function() {
    var data = [];      
    $(this).find('tr').each(function(){
        var row = {};
        $(this).find('input,textarea').each(function(){
            row[$(this).attr('name')] = $(this).val();
        });
    });
    return data;
  }
})( jQuery );

// Usage:

$.post("test.php", { 'mydata': $('table').tableData() } );


回答2:

You have two different variables with the exact same ID, 5030c9261eca0. An ID should be unique for a given HTML page.

Give each element a unique ID.

Instead, give each element that you want to locate a shared class, e.g. needToPost, and use that class:

$my_array = $(".needToPost").map(function () { return $(this).is("input")?$(this).val():$(this).text(); } );