I have a main div and inside of this, there are a lot of input text and radio button.
Like this:
<div id="mainDiv">
<input type="text" name="text-1" /> <br/>
<input type="radio" name="radio-1" />Yes
<input type="radio" name="radio-1" />No <br/>
<input type="text" name="text-2" /> <br/>
<input type="text" name="text-3" /> <br/>
</div>
<img src="img/img.gif" onclick="getAllValues();" />
I want to define the function getAllValues()
in jQuery to get all values in mainDiv
and save them in a string.
It is possible?
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.
Try something like that:
function getAllValues() {
var allVal = '';
$("#mainDiv > input").each(function() {
allVal += '&' + $(this).attr('name') + '=' + $(this).val();
});
alert(allVal);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With