【问题标题】:How to get the values of all textfields in add/remove textfields and form JSON如何在添加/删除文本字段和表单 JSON 中获取所有文本字段的值
【发布时间】:2014-07-31 14:19:05
【问题描述】:

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

下面是代码-

$(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。

【问题讨论】:

  • 首先更新到当前版本的 jQuery,并使用on 而不是live。它不会解决你的问题,但使用 5 年前的 jQuery 版本肯定也无济于事。
  • @adeneo 你的意思是它对创建 JSON 没有帮助
  • 您希望 JSON 的结构如何?是否要将输入名称作为键?
  • @PatrickQ 我可以举个例子{"welcomesList":["Thanks for calling us","Please give the list"]}

标签: javascript jquery json


【解决方案1】:

遍历输入字段,获取它们的值,然后将它们推送到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,而不是我在上面为 PAtrickQ 发布的那个
  • 我可以举个例子{"welcomesList":["Thanks for calling us","Please give the list"]}
  • 那么,您基本上希望数组只填充来自输入字段的值?这是你要找的吗? jsfiddle.net/tZPg4/11015
  • @Wedvich 您所做的是针对整个表单。如果我必须只为输入字段(比如 p_scents)做这件事。我该怎么做。
【解决方案2】:

我不知道这是否是最好的解决方案,因为我正在构建一个字符串而不是 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 + "}";
    });
});

【讨论】:

    猜你喜欢
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2021-09-22
    相关资源
    最近更新 更多