We help IT Professionals succeed at work.

jQuery: how to collect values of checked, selected or entered text from form elements by class

Brad Bansner
Brad Bansner asked
on
Lets say I have a bunch of form elements with the same class:
1. <input type="text" class="answer1">
2. <input type="radio" class="answer1" value="123">
3. <input type="checkbox" class="answer1" value="abc">

I need to write a function that will get all the values entered by the user:
1. Any text they typed into a text box
2. The value of a radio button, if selected
3. The value of a check box, if checked

I need to be able to loop through all the entered/select values, so I can handle each one individually. I know how to get single values, such as:

$('.answer1').val();
$('.answer1').attr('checked'), true);

...etc. But if there are a variety of types of form elements on the same page, is there some relatively easy way to do this? Possibly, I need to setup separate loops, one for each type of form element, and then combine those into a list? Not sure that it would be a good idea to do a attr('checked') on a text box, though.

Would appreciate any advice. Thank you!
Comment
Watch Question

Multitechnician
Distinguished Expert 2019
Commented:
check this : http://jsfiddle.net/rkqPU/ 
var array = $("input,select,textarea", "form");

$.each(array, function(i,el) {
    alert(el.value);
})

Open in new window

Brad BansnerWeb Developer

Author

Commented:
That's pretty cool. Two things:

1. Can this be modified to limit the form elements by class?

2. This displays the value of all checkboxes and radio buttons, whether they are selected or not. I would only want values that the user selected.
Commented:
2. You can use $('input[type="checkbox"]:checked') to select the checked checkbox.
Brad BansnerWeb Developer

Author

Commented:
Cool, thank you. I think I know what to do now.