Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Datepicker for multiple inputs

I have a jQuery datepicker script:

$(function() {
    $( "#datepicker" ).datepicker({ dateFormat: "yyyy-mm-dd" });
}); 

When I want to initialize this script for two inputs, it works only for the first one. How to use it for both inputs?

<input type="text" name="MyDate1" id="datepicker">
<input type="text" name="MyDate2" id="datepicker">
like image 901
Gusgus Avatar asked May 29 '12 16:05

Gusgus


2 Answers

Just change all id to class.

<input type="text" name="MyDate1" class="datepicker">
<input type="text" name="MyDate2" class="datepicker">

$(function() {
  $( ".datepicker" ).datepicker({ dateFormat: "yyyy-mm-dd" });
}); 

also can use

$(function() {
  $( "input[name^=MyDate]" ).datepicker({ dateFormat: "yyyy-mm-dd" });
});
like image 78
thecodeparadox Avatar answered Sep 24 '22 03:09

thecodeparadox


You could also add classes on the fly if input fields are dynamically generated, such as in Django templates.

<input type="text" name="MyDate1" id="datepicker1">
<input type="text" name="MyDate2" id="datepicker2">

Get input fields using #id and add a class

$(function() {
    $( "#datepicker1, #datepicker2" ).addClass('datepicker');
    $( ".datepicker" ).datepicker({ dateFormat: "yy-mm-dd" });
});
like image 36
Staccato Avatar answered Sep 22 '22 03:09

Staccato