Get all input in div for ajax request

I am trying to get all input text boxes, radio groups, checkboxes, etc. I'm having problems getting the selected radio values ​​and checkboxes, I can’t figure it out.

I can get the text fields, but I can not get the "selected" in the right place. At the moment, it just gets the first value for the radio / flags, not the selected value.

$('#form_1 input').each(function(key)               
    formData += '&'+$('#'+this.id).attr('name')+'='+$('#'+this.id).val();   
});

thank

EDITED

$('#form_1 input').each(function(key, value) {              
    if ((this.type === "radio" || this.type === "checkbox") && this.checked === true) {
         val = this.value;
    } else {
         val = this.value;
    }

    alert($('#'+this.id).attr('name') + ' = ' + val);
    formData += '&'+$('#'+this.id).attr('name')+'='+val;    
});

Ok, now I get every value for radio stations, etc., so I'm one step closer. You just need to get the values ​​of the selected radio stations.

thank

+3
source share
3 answers
var val;
if (this.type === "radio" || this.type === "checkbox") {
     val = this.checked;
} else {
     val = this.value;
}

For radio stations and checkboxes, you need the checked attribute.

Update

You wrote

(this.type === "radio" || (this.type === "checkbox" && this.checked === true))

You meant

((this.type === "radio" || this.type === "checkbox") && this.checked === true)

You need these brackets in the right place.

Further editing

.

, .

if ((this.type === "radio" || this.type === "checkbox") && this.checked === false) {
    return;
}

, /, .

+2

serialize() [docs].

, .

var formData = $('#form_1').serialize();

:

.serialize() jQuery, , , . , :

$('form').submit(function() {
  alert($(this).serialize());
  return false;
});

:

a=1&b=2&c=3&d=4&e=5
+3

This does not answer your question directly, but it looks like you are trying to achieve something already available - you can check serialize()- use it asvar formData = $('#form_1').serialize()

0
source

All Articles