Adding all TextBox values to a Hidden field using jQuery

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.






About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

5 comments:

Anonymous said...

Could not tortured and use the methods serialize. http://api.jquery.com/serialize/

$("form :input[type=text]").serialize()

Unknown said...
This comment has been removed by the author.
Amit said...

Although this is very nice article But Can be any other way for binding "javascript to $("#input").val(data.id) without using textbox id".

Here i don't want to bind value with textbox id. how it can be done.

Suprotim Agarwal said...

Did you try $("input:hidden]").val(data.join(" ")); -- untested

Social Blogsite said...

Will that prevent all the seialized inputs from being sent along with the serialized one in a GET form?
(to make the query string shorter)
Or do you have to disable them by script?