Reputation: 15713
I'm using jQuery 1.4.4 and I'm stuck trying to add a datepicker dynamically by id. Here is the code:
$(function () {
$('#ListTableBody').find('input[id^="PickDate."]').each(function () {
alert(this.id);
$(this.id).datepicker();
});
});
I'm using a table that dynamically generates the id's on the fly. The code above finds each of the id's and I verified it using the alert. As I loop through, this.id shows I've got the right id and input, but the datepicker doesn't work for some reason? Also, I don't throw any errors.
Any ideas what I'm doing wrong here?
Upvotes: 0
Views: 1442
Reputation: 21
could put the same class for each control you need to use as a datepicker.
<script>
$(function() {
$('.class').datepicker();
});
</script>
Upvotes: 0
Reputation: 39399
I'd use a class instead. IDs are only supposed to be used once per document, and the fact you're applying each()
to your ID selector suggests you may have more than one instance on your page.
Instead, opt for a descriptive class name such as .datepicker
. Advantage is you can then have more than one on your page, and can also initialise datepickers on them with an expression like such:
$(document).ready(function() {
$('input.datepicker').datepicker();
});
No need for the each()
loop if you're not doing anything else. If you want to restrict datepickers to inputs within a certain area, such as #ListTableBody
(which I'd again advise the use of a class name so you can have more than one on your page if you wish) then just change the selector:
$(document).ready(function() {
$('#ListTableBody').find('input.datepicker').datepicker();
});
Upvotes: 1
Reputation: 11633
You'd need to do something like this if you want to use the ID for it:
$("#"+this.id).datepicker();
But it's much easier to just do:
$(this).datepicker();
Upvotes: 1
Reputation: 38147
Try this :
$('#ListTableBody').find('input[id^="PickDate."]').each(function() {
$(this).datepicker();
});
no need to get the id
attribute - you can make this
a jQuery object immediately
Upvotes: 3