Automatically get values of all element inside a div with jQuery
Try something like that:
function getAllValues() {
var allVal = '';
$("#mainDiv > input").each(function() {
allVal += '&' + $(this).attr('name') + '=' + $(this).val();
});
alert(allVal);
}
To achieve this you can select all the form fields and use map()
to create an array from their values, which can be retrieved based on their type
. Try this:
function getAllValues() {
var inputValues = $('#mainDiv :input').map(function() {
var type = $(this).prop("type");
// checked radios/checkboxes
if ((type == "checkbox" || type == "radio") && this.checked) {
return $(this).val();
}
// all other fields, except buttons
else if (type != "button" && type != "submit") {
return $(this).val();
}
})
return inputValues.join(',');
}
The if
statement could be joined together here, but I left them separate for clarity.