Search This Blog

Sunday, April 8, 2012

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>

No comments:

Post a Comment