开发者

return type of input with jquery

I have a form with dynamically created form elements.

开发者_如何学Go

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?


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


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()); });


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);
  }
});


try:

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


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">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜