September 12, 2009

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Access Values from All or Selected Textboxes using jQuery"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions