开发者

Serialize inputs in table rows (jQuery)

I have a table with multiple rows which contain form inputs (checkboxes, text, dropdowns). When I click save I want to be able to get JSON representing each table row which will be used in an AJAX request. Each row has an id on it so I would like to get back something like this:

[1: { "input_name":"input_value", "input_name":"input_value", etc...}, 2: {etc...}]

With those numbers being the id of the table开发者_如何学Go row.

Any way to do this?


This should do what you need:

<table>
    <tr id="101">
        <td><input type="text" name="f1" value="" /></td>
        <td><input type="checkbox" name="f2" value="v2" /></td>
        <td><input type="checkbox" name="f3" value="" /></td>
        <td><select name="f4">
                <option>1</option>
                <option>2</option>
                <option>3</option>
            </select></td>
    </tr>
    <tr id="102">
        <td><input type="text" name="f1" value="" /></td>
        <td><input type="checkbox" name="f2" value="v2" /></td>
        <td><input type="checkbox" name="f3" value="" /></td>
        <td><select name="f4">
                <option>1</option>
                <option>2</option>
                <option>3</option>
            </select></td>
    </tr>
    <tr id="103">
        <td><input type="text" name="f1" value="" /></td>
        <td><input type="checkbox" name="f2" value="v2" /></td>
        <td><input type="checkbox" name="f3" value="" /></td>
        <td><select name="f4">
                <option>1</option>
                <option>2</option>
                <option>3</option>
            </select></td>
    </tr>

</table>
<button id="btnGo">Go</button>
<script type="text/javascript">
    $('#btnGo').click(function(){
        var data={};
        $('table').find('tr').each(function(){
            var id=$(this).attr('id');
            var row={};
            $(this).find('input,select,textarea').each(function(){
                row[$(this).attr('name')]=$(this).val();
            });
            data[id]=row;
        });
        console.log(data);
    });
</script>


Haven't tested but something like this should work

var myjson = new Object();
$("#tableid > tr").each(function () {
  var tablerow = $(this);
  $("td input", tablerow).each(function () {
    var input = $(this);
    myjson[tablerow.attr("id")][input.attr("name")] = input.val();
  });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜