Access Values from All or Selected Textboxes using jQuery

I have seen a lot of users asking an easy and effective way to access values from all TextBoxes using jQuery. This post demonstrates that. I added a couple of extra requirements:

- The selected values should be listed separately on each line with minimal efforts.

- Empty Textboxes should be ignored.

Here’s the code:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Access Values from All or Selected Textboxes</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("#btnAll").click(function(e) {
$("p").text('').append($("input[type=text]").map(function() {
return $(this).val() || null;
}).get().join("<br/> "));
});

$("#btnSel").click(function(e) {
$("p").text('').append($("input.selected").map(function() {
return $(this).val() || null;
}).get().join("<br/> "));
});
});
</script>
</
head>
<
body>
<
input id="tb1" type="text" /><br />
<
input id="tb2" type="text" /><br />
<
input id="tb3" type="text" /><br />
<
input id="tb4" type="text" class="selected" /><br />
<
input id="tb5" type="text" /><br />
<
input id="tb6" type="text" class="selected"/><br />
<
input id="btnAll" type="button" value="Select All" />
<
input id="btnSel" type="button" value="Select Some" /><br />
<
p></p>

</
body>
</
html>

As you can observe, the code is triggered on Button Clicks. The first piece of code is invoked when the user clicks on ‘btnAll’. The code selects the value of all textboxes using the Traversing/Map function. Only the textboxes with some text in it are displayed. This is done using the $(this).val() || null; statement

Similarly on the click of ‘btnSel’, those textboxes which have class='”selected” are displayed.

image

You can see a Live Demo



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: