序列化表行中的输入(jQuery) [英] Serialize inputs in table rows (jQuery)

查看:82
本文介绍了序列化表行中的输入(jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多行的表,其中包含表单输入(复选框,文本,下拉列表).当我单击保存时,我希望能够获取表示将在AJAX请求中使用的每个表行的JSON.每行上面都有一个ID,所以我想找回这样的东西:

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...}]

这些数字是表格行的ID.

With those numbers being the id of the table row.

有什么办法吗?

推荐答案

这应该可以满足您的需求:

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>

这篇关于序列化表行中的输入(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆