jQuery Datepicker for multiple inputs
47,682
Solution 1
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" });
});
Solution 2
Tired of repeating this, but still, am repeating it once more. id
s have to be unique. So, use this:
<input type="text" name="MyDate1" class="datepicker">
<input type="text" name="MyDate2" class="datepicker">
with
$(function() {
$( ".datepicker" ).datepicker({ dateFormat: "yyyy-mm-dd" });
});
Solution 3
It isn't valid to have duplicated IDs. You should add a class instead:
<input type="text" name="MyDate1" class="datepicker" id="datepicker1">
<input type="text" name="MyDate2" class="datepicker" id="datepicker2">
Then you can do:
$(function() {
$( ".datepicker" ).datepicker({ dateFormat: "yyyy-mm-dd" });
});
Solution 4
Access datepicker function by Name:
$(function() {
$('[name="MyDate1"]').datepicker({ dateFormat: "yyyy-mm-dd" });
});
Solution 5
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" });
});
Author by
Gusgus
Updated on July 09, 2022Comments
-
Gusgus almost 2 years
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">