views:

186

answers:

6

I have a form with dynamically created form elements.

I need to get the value of each element, and send an ajax request to make sure the data is ok (the easy part). I can get each elements value easy enough, but the problem comes in with radio buttons. For example:

<input type = 'radio' class = 'form_element' value = '1'>
<input type = 'radio' class = 'form_element' value = '1'>
<input type = 'radio' class = 'form_element' value = '1'>

if i do something like...

$('.form_element').each(function(){
     alert($(this).val());
});

it will print the values of all of the radio buttons, regardless if it is checked or not.

I need it to only return the value of the one that is checked.

So, is there a way to return the type of an input element from jquery?

A: 

Use $('.form_element:checked') to get only the value of the checked radio buttons.

salgiza
A: 

try:

$('.form_element:checked').each(function(){
     alert($(this).val());
});
The MYYN
A: 

yes, i have thought of this, but the problem with that is each element with a class of form_element could be a radio button, or a text box, or a select box, or even a textarea.

The order they get returned in is important, which is why i wanted to select them with a common class name.

So, the checked selector wont work for anything other then radio and checkbox.

kris
Use the add comment option to reply to peoples answers as the order the answers display in can change - which would stop this from making sense.
Sohnee
+1  A: 

Besides salgiza has mentioned, you can also use Attribute filters to perform more generic filtering including your requirement.

Like: $('.form_element[checked=true]').each(function(){ alert($(this).val()); });

A: 

This example could probably be improved, but should do the trick.

$('.form_element').each(function(){
    if ($(this).attr("type") == "radio") {
        if ($(this).attr("checked") == true) {
            alert($(this).val());
        }
    } else {
        alert($(this).val());
    }
});

I tested it using the following HTML, in order to tell if it was working (your example had the same value on each radio option):

<input type='radio' name="a" class="form_element" value="1">
<input type='radio' name="a" class="form_element" value="2">
<input type='radio' name="a" class="form_element" value="3">
Sohnee
+1  A: 

This does what you want. Inside the loop it left away the unneeded jQuery boxing. Handles radio, checkbox, text, textarea, select-one. Doesn't account for select-multiple, file, ....

$('.form_element').each(function() {
  switch(this.type) {
    case 'radio':
    case 'checkbox': if (this.checked) alert(this.value); break;
    case 'text':
    case 'textarea':
    case 'select-one': alert(this.value); break;
    default: alert("unhandled type: "+this.type);
  }
});
jitter