【问题标题】:Updated text fields to JSON string - Javascript/JQuery [duplicate]将文本字段更新为 JSON 字符串 - Javascript/JQuery [重复]
【发布时间】:2014-06-22 00:56:47
【问题描述】:

我有一个动态表单,其中包含文本字段,当需要更新时它们会变为输入框。

当它们被更新并且用户点击提交时,我想将更新后的值添加到我可以发布到 ASP.NET 脚本的 json 字符串中。

这是表格中2行的html:

<tr id="1">
<td onclick="">Colleague 1:</td>
<td id="c1nametxt" onclick="">
    <input id="c1nametb" type="text" value="Bob">
</td>
<td id="c1unametxt" onclick="">
    <input id="c1unametb" type="text" value="bjones">
</td>
<td id="c1eaddtxt" onclick="">
    <input id="c1eaddtb" type="text" value="bjones@company.co.uk">
</td>
<td id="c1pnotxt" onclick="">
    <input id="c1pnotb" type="text" value="0111122224">
</td>
<td id="c1exttxt" onclick="">
    <input id="c1exttb" type="text" value="22224">
    <span onclick="delrec(this)">Del</span>
</td>

<tr id="2">
     <td onclick="">Colleague 2:</td>
<td id="c2nametxt" onclick="">
    <input id="c2nametb" type="text" value="John">
</td>
<td id="c2unametxt" onclick="">
    <input id="c2unametb" type="text" value="jhill">
</td>
<td id="c2eaddtxt" onclick="">
    <input id="c2eaddtb" type="text" value="jhill@company.co.uk">
</td>
<td id="c2pnotxt" onclick="">
    <input id="c2pnotb" type="text" value="0111122225">
</td>
<td id="c2exttxt" onclick="">
    <input id="c2exttb" type="text" value="22225">
    <span onclick="delrec(this)">Del</span>
</td>

这是我用来检测哪些输入框已更新的 jQuery:

$("#subdetails").click(function () {
    $("#mantab input[type=text]").each(function () {
        if ($(this).val() !== this.defaultValue) {               

             //code to create json string   

        }
    });
 });

如果以下字段已更新,这是我想创建的 json 字符串示例:

{
"1":{
    "c1nametb": "newname",
    "c1exttb": "22227",
    }
"2":{
    "c2eaddtb": "neweadd@company.co.uk",
    "c2pnotb": "0111122210",
    }
}

谁能帮我创建这个字符串的代码,或者建议一个更好的方法?

谢谢 瑞恩

【问题讨论】:

  • 我只想将更新后的字段转换为字符串,而不是整个表单。
  • 维护一个数组(或对象),为每个字段存储一个布尔值,并在字段更新时将值翻转为 true。
  • 查看this...
  • 我已经能够通过将默认值与当前值进行比较来检查哪些字段已更新。
  • 它只是将这些特定字段转换为我可以传递给 asp.net scipt 的 json 字符串

标签: javascript jquery json


【解决方案1】:

这是解决方案,遍历每一行,找到文本框的值并将其推送到数组,最后将其转换为字符串。您可以在隐藏字段中设置该字符串以将其传递到服务器端。

var ArrColleague = [];

$("#subdetails").click(function () {
    $("#mantab tr").each(function (index, val) {
        ArrColleague.push({
            "c1nametb": $(val).find("#c" + $(val).attr("id") + "nametb").val(),
            "c1unametb": $(val).find("#c" + $(val).attr("id") + "unametb").val(),
            "c1eaddtb": $(val).find("#c" + $(val).attr("id") + "eaddtb").val(),
            "c1pnotb": $(val).find("#c" + $(val).attr("id") + "pnotb").val(),
            "c1exttb": $(val).find("#c" + $(val).attr("id") + "exttb").val()
        });
    });
});

var JsonString = JSON.stringify(ArrColleague);

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多