Reputation: 61
I know how to get all form elements with their values in one single array with jquery with the ".each" method. If I alert the :input[type:text] element values i can see them - but if I want to alert the value of any checkbox in this very same array it always displays "on".
It is somehow possible to have the content elements of the form: 1) in one array, + 2) that it shows me the value of textfields and the checked-status of checkboxes too ?
I want to be able to iterate through this form elements array and validate the data but i cant determine the checked state of the checkboxes in this mixed array.
Hope it's not too confusing regards
Upvotes: 0
Views: 6323
Reputation: 5181
Try using .checked instead of .value. That will give you a true/false status.
When you iterate through the list, check element.type to determine how to handle it. So for example
if (element.type == "checkbox") {
//use element.checked
} else {
//use element.value
}
Upvotes: 1
Reputation: 324567
Skip jQuery and use the DOM. There's a convenient elements
property of the form that contains all the form controls (inputs, selects, buttons, etc.) within the form. Use the type
and tagName
properties of each element to distinguish between them, and use the Boolean checked
property of checkboxes and radio buttons to see if they're checked or not. This stuff works perfectly in all major scriptable browsers ever released.
Trivial example:
var els = form.elements;
for (var i = 0, len = els.length; i < len; ++i) {
if (els[i].tagName == "INPUT") {
if (els[i].type == "checkbox" || els[i].type == "radio") {
alert("Checked: " + els[i].checked);
} else {
alert("Value: " + els[i].value);
}
}
}
Upvotes: 2
Reputation: 3171
Take a look at this to see how this is done:
You will be able to see the value of every input text and checkbox. I have them in alerts, but you can just assign them to variables or whatever you want. The magic is that the jQuery Selector (reference for the one I used is here: http://api.jquery.com/multiple-attribute-selector/) allows you to grab selected portions of your form.
To get the "value" of a checkbox, you'll want to check the $(this).attr('checked') method's value instead, where this is the current checkbox element you're iterating over.
Upvotes: 1
Reputation: 14859
If you're just trying to get the data from your form, then use .serializeArray as Rusty mentioned. However, if you're trying to do this for form validation, then you might be better of implementing the jQuery Validate plug-in.
Upvotes: 0
Reputation: 1426
Did you take a look at .serializeArray()? I think this might do exactly what you're looking for.
Upvotes: 3