I was recently asked on one of the ASP.NET forums how to store all the values of every text box in a hidden field using JavaScript. I immediately said use jQuery! And this is what I came up with:
<html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title></title> <script src="http://code.jquery.com/jquery-latest.js" language="javascript" type="text/javascript"></script> <script language="javascript" type="text/javascript"> $(function() { $("#Button1").click(function(event) { var data = []; var form = $("form :input[type=text]"); $.each(form, function(e, textBox) { data.push($.trim(textBox.value)); }); $("#HiddenAddressData").val(data.join(" ")); }); }); </script> </head><body> <form> <input id="Address1" type="text" /><br /> <input id="Address2" type="text" /><br /> <input id="State" type="text" /><br /> <input id="Zip" type="text" /><br /> <input id="Button1" type="button" value="button" /> <input id="HiddenAddressData" type="hidden" /> </form></body></html>
What I’m doing is looping through each form element and adding it to my JavaScript array:
var data = [];var form = $("form :input[type=text]");$.each(form, function(e, textBox) { data.push($.trim(textBox.value));});
Then I join all the element of the array into a single value that is copied to the hidden field:
$("#HiddenAddressData").val(data.join(" "));
Nice and simple.
From DevCurry
