Reputation: 9977
I have a form with multiple input fields that use datepicker. I have just created IDs for them and this has worked fine but now I need to use it in an instance where there are multiple forms shown on the same page.
Is there any way to create a jQuery function that will dynamically add an ID to any element with the class of "datepicker" and make the datepicker work on theses elements?
Something like:
$('.datepicker').append('ID','datepicker + (1)');
$("#datepicker + (1)").datepicker();
I know this will not actually work but I thought it was the easiest way to explain, the +(1) suffixes a number to the ID.
My current code for the static elements works like this.
$("#datepicker").datepicker();
$("#datepicker01").datepicker();
$("#datepicker02").datepicker();
$("#datepicker03").datepicker();
$("#datepicker04").datepicker();
$("#datepicker05").datepicker();
$("#datepicker06").datepicker();
Thanks for the help, cheers :)
Upvotes: 0
Views: 16993
Reputation: 1
Hello I tried this binding using Spring MVC 3.0 and... It works, nice ! I have the script
<script type="text/javascript">
$(function(){
$(".datepicker").datepicker({ dateFormat:"dd/mm/yy" });
});
</script>
and then, in my case, working with JSP and JSTL I was able to bind a JQueryPicker to my elements that are created dinamically, and here is a piece of code, if you see a when it's becuase I am working on more things, but the idea is the same:
<c:when test="${fieldVar.type == 'DATE'}">
<td><form:input path="fieldWrapperElements[${status.index}].dateValue"class="datepicker"/></td>
</c:when>
Upvotes: 0
Reputation: 434755
You don't need the IDs at all, you can just bind them all at once with this:
$('.datepicker').datepicker();
Demo: http://jsfiddle.net/ambiguous/ua4bc/
Most plugins can bind to multiple elements at once, that's why almost all of them look like:
return this.each(function() { ... });
inside.
If you needed the IDs for some other purpose then you could just do this:
$('.datepicker').each(function(i) {
this.id = 'datepicker' + i;
}).datepicker();
Demo (use your DOM inspector to see the IDs): http://jsfiddle.net/ambiguous/6zfEY/
Upvotes: 4
Reputation: 146219
$(function(){
$('.datepicker').each(function(i){
$(this).attr('id', $(this).attr('class')+parseInt(i+1));
});
// You can call like
$("#datepicker1").datepicker();
$("#datepicker2").datepicker();
$("#datepicker3").datepicker();
});
but I think you don't need to add id
, anyways.
Upvotes: 2