Reputation: 2597
I have 3 fields:
<input type="datetime" name="input-data" id="datetime-start">
<input type="datetime" name="input-data" id="datetime-end">
<input type="text" name="input-data" id="text-basic">
And i need to check if there is something entered, so i firsly did it like jQuery.each('[name="input-data"]', function()
and used this
in loop, but get some errors. After small debug i found a way like jQuery.each(jQuery('[name="input-data"]'), function(key, value)
, but when i trying to do console.log(value.val());
i get en error. So i decided to look what is in value
and was surprised - there was just a string <input type="datetime" name="input-data" id="datetime-start">
. So how can i loop trough all input values?
Upvotes: 1
Views: 309
Reputation: 224
you're working on HTML5, aren't you? why don't you use the given validation of html5? Just set attribute "required='true'" and you should be done ;-)
there is also a good way to do this in jquery mobile. if i remember it correctly, you have to set the class 'required' to the wanted input attributes. For reference:
Upvotes: -1
Reputation: 66188
You're using .each()
incorrectly. Try this:
jQuery('[name="input-data"]').each(function() {
// Use $(this) to access current object
});
Upvotes: 0
Reputation: 7954
$(document).ready(function(){
$('input').each(function(){
console.log($(this).val());
});
}
});
Upvotes: 0
Reputation: 388406
Try
$('input[name="input-data"]').each(function(el){
console.log($(this).val());
})
Demo: Fiddle
Upvotes: 0
Reputation: 1075129
You use each
on a jQuery instance, e.g.:
jQuery('[name="input-data"]').each(function() {
// Here, `this` is the DOM element. If you want to use jQuery methods,
// wrap the element in a jQuery instance:
var input = jQuery(this);
// Now, input.val() will give you the value
});
jQuery's API is sometimes a bit confusing. This is one of those times. jQuery has two similar but different functions: The each
you call on jQuery instances (see above), and jQuery.each
, which you can use to loop through arrays, objects, and array-like objects.
Your code using jQuery.each(jQuery('[name="input-data"]', function...
does work, because jQuery instances are array-like, but then within the function you weren't wrapping the DOM element, which is why val()
didn't work. But the above is the normal way to loop through a set of matched elements.
Upvotes: 2