Let suppose we want to access values from all ASP.NET Textboxes on a Button click. Empty Textboxes should be ignored.

JQuery Section:

<script type="text/javascript">
$(function () {
$('input[id$=btnAll]').click(function (e) {
e.preventDefault();
$("#para").text('')
.append($("input:text").map(function () {
return $(this).val() || null;
}).get().join("<br/> "));
});
});
</script>

Explanation:
To achieve this requirement,$.map() is an extremely useful function which saves us from writing many steps. This function transforms an array into another array by using a filter function and then allows us to access individual items of the array and modify them.
In the code shown above, on the button (btnAll) click, the postback is prevented using e.preventDefault().The content of the paragraph is reset ($(“#para”).text(”)) and we then use a Selector to match all input elements of type text (input:text). The $.map() method iterates through all the textboxes on the page and invokes a filter function to select the non-empty textboxes. The results are appended to a paragraph (para) and displayed individually using a line break (<br/>).

Complete code

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Access Values from All TextBoxes using jQuery</title>
<link href="../CSS/Demos.css" rel="stylesheet" type="text/css" />
<script type='text/javascript' src='../Scripts/jquery-1.3.2.min.js'>
</script>
<script type="text/javascript">
$(function () {
$('input[id$=btnAll]').click(function (e) {
e.preventDefault();
$("#para").text('')
.append($("input:text").map(function () {
return $(this).val() || null;
}).get().join("<br/> "));
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="divMain">
<h2>Access Values from All TextBoxes using jQuery (Empty Text will be ingnored)</h2><br />
<asp:TextBox ID="txtBox1" runat="server" Text="Text Box 1" /><br />
<asp:TextBox ID="txtBox2" runat="server" Text="Text Box 2"/><br />
<asp:TextBox ID="txtBox3" runat="server" Text="Text Box 3"/><br />
<asp:TextBox ID="txtBox4" runat="server" Text="Text Box 4" /><br />
<asp:Button ID="btnAll" runat="server" Text="Display All" ToolTip="Click to display text from all boxes" />
<br/><p id="para"></p>
</div>
</form>
</body>
</html>

Output

 

Leave a Reply

Your email address will not be published. Required fields are marked *