I have a form with a bunch of text inputs like this:
<input type="text" name="option[]" value="option 1" onBlur="outputOptions()">
<input type="text" name="option[]" value="option 2" onBlur="outputOptions()">
<input type="text" name="option[]" value="option 3" onBlur="outputOptions()">
I want to be able to get the values of all of the inputs, so I tried doing this:
function outputOptions()
{
console.log("inside outputOptions");
$("input[name=option]").each(
function() {
console.log("option value: " + $(this).value);
}
);
}
On my site the result is that when I click in and out of a text input I see "inside outputOptions," but none of the text input values are printed out.
What am I doing wrong?
JSFiddle: http://jsfiddle.net/6zguZ/2/
You're getting the value the wrong way:
console.log("option value: " + this.value);
If you really want to use jQuery, you'd do:
console.log("option value: " + $(this).val());
but there's no reason to do that.
You also need to select using the actual name:
$('input[name="option[]"]').each(
It's not an error for a jQuery selection to match no elements, so you get no error for something like that.
Try this Vanilla JS :
var inputs = document.getElementsByName("option[]"), l = inputs.length, i;
for( i=0; i<l; i++) {
console.log(inputs[i].value);
}
EDIT: Here's a speed test to show why this is better than jQuery.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.