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.
Tweet
5 comments:
Could not tortured and use the methods serialize. http://api.jquery.com/serialize/
$("form :input[type=text]").serialize()
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.
Did you try $("input:hidden]").val(data.join(" ")); -- untested
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?
Post a Comment