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.

Edit for clarity

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.

Update on Answer

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');
        })
});
Was it helpful?

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:

http://jsfiddle.net/z88KG/

$("[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(); });

Example Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top