You don't need to iterate.. If you call .datepicker()
on a collection, it will be applied to all the elements in the collection:
$("[id$='Date']").datepicker();
Question
I'm trying to use a simple datepicker in an MVC application and need to call the datepicker whenever one of the input fields has an id
ending in Date
.
The field names are picked up from the view models and I'd prefer to have as little additional information attached as possible (e.g. I could add a different class to each input and script a datepicker for each one but that seems like overkill).
I can create an array of elements and can call each one by it's index.
var dateSelect = [];
$("[id$='Date']").each(function() {
dateSelect.push('#' + $(this).attr('id'));
console.log(dateSelect);
});
$(dateSelect[0]).datepicker({ format: "dd/mm/yyyy" });
How can I change this to call the datepicker for every instance of a Date field without knowing how many there are in the array?
e.g. $(dateSelect[ANY]).datepicker({ format: "dd/mm/yyyy" });
I've tried using each
and a for loop
but the datepicker only seems to appear if it's called directly after the field element.
Judging by the first few comments I may not have been clear on why I need to answer this question.
When I call the datepicker on a page with multiple date fields, any actions called on the datepicker (e.g. onChange) are only applied to the first instance no matter which field is actually in focus.
I thought using an array of field elements would make it simple to call each one individually. I need to know how to make the call to an unknown number of elements in the array, as per the example:
$(dateSelect[ANY]).datepicker({ format: "dd/mm/yyyy" });
The question is not how to attach a datepicker to multiple fields.
The following code works. The original problem I was having was caused by the datepicker having two different samples showing different methods for hiding. For some reason the one I was trying to use only attached to the first instance of a date field on the page.
$("[id$='DateInput']").datepicker({ format: "dd MM yyyy" }).focus(function() {
$(this).on('changeDate', function () {
$(this).datepicker('hide');
})
});
Solution
You don't need to iterate.. If you call .datepicker()
on a collection, it will be applied to all the elements in the collection:
$("[id$='Date']").datepicker();
OTHER TIPS
Why not just create the datepicker
instance within each iteration of each
?
$("[id$='Date']").each(function() {
$(this).datepicker({ format: "dd/mm/yyyy" });
});
If you add a class to all those inputs such as .datepicker
you won't need to script a datepicker for each one just include one reference to the class you use.
$(function(){ $(".datepicker").datepicker(); });