如何在添加/删除文本字段和表单JSON中获得所有文本字段的值

How to get the values of all textfields in add/remove textfields and form JSON

本文关键字:文本 字段 JSON 添加 删除 表单      更新时间:2023-09-26

我使用插件来复制添加和删除按钮上的文本字段。现在,在添加和删除字段之后,我想要从所有文本字段中生成JSON并在提交时POST它。

下面是代码-
$(function () {
    var scntDiv = $('#p_scents');
    var i = $('#p_scents p').size() + 1;
    $('#addScnt').live('click', function () {
        $('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
        i++;
        return false;
    });
    $('#remScnt').live('click', function () {
        if (i > 2) {
            $(this).parents('p').remove();
            i--;
        }
        return false;
    });
});  
可以引用

JSFiddle。我想获得所有文本字段的值,并形成JSON。

遍历输入字段,获取它们的值,并将它们推入JSON.stringify以创建所需的JSON。

function serializeAndPost() {
    var values = [];
    $( '#p_scents input[id^=p_scnt_]' ).each( function ( index, element ) {
        values.push( element.value );
    } );
    var json = JSON.stringify( { "welcomesList": values } );
    // Do your POSTing here
}

更新小提琴:https://jsfiddle.net/tZPg4/11019/

我不知道这是否是最好的解决方案,因为我正在构建一个字符串而不是JSON对象,但这是我的解决方案:

HTML

<input type="button" id="btnSubmit" value="Submit"></input>

JS:

$(function () {
    var scntDiv = $('#p_scents');
    var i = $('#p_scents p').size() + 1;
    $('#addScnt').live('click', function () {
        $('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
        i++;
        return false;
    });
    $('#remScnt').live('click', function () {
        if (i > 2) {
            $(this).parents('p').remove();
            i--;
        }
        return false;
    });
    $('#btnSubmit').click(function(e) {
        e.preventDefault();
        var str = [];
        $.each($('input[type=text]'), function(i, val) {
            var el = $(this);
            str.push('"' + el.attr("id") + '":"' + el.val() +'"');
        });
        var json_string = "{" + str + "}";
    });
});