2

I have a dynamic form that has text fields which change to input boxes when they need to be updated.

When they have been updated and the user clicks submit I want to add the updated values to a json string which i can post to an ASP.NET script.

Here is the html of 2 rows in the table:

<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>

Here is the jQuery I'm using to detect which input boxes have been updated:

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

             //code to create json string   

        }
    });
 });

This is an example of a json string i would like to create if the following field were updated:

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

Can any one please help me with the code to create this string, or advise on a better way of doing this?

Thanks Ryan

rbradshaw
  • 35
  • 5

1 Answers1

1

Here is the solution, iterate through each row, find values of textbox and push it to array and finally convert it to string. you can set that string in hidden field to pass it to server side.

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);
Rashmin Javiya
  • 5,173
  • 3
  • 27
  • 49