jQuery extract id and then attach calendar based on class
I'm working with an existing javascript library that does an AJAX call and then executes an optional callback function. The callback function gets passed the HTML string that is being loa开发者_JS百科ded into the DOM. I need to assign the jQuery datepicker to all elements in that HTML string that are of calendar class.
A simplified example of the HTML string from the AJAX query is:
<tr id='1234'>
<td>
<input type="text" value="somevalue" />
<input type="text" class="calendar" value="21/12/2010" />
</td>
<td>
<input type="text" value="someothervalue" />
<input type="text" class="calendar" value="21/12/2011" />
</td>
</tr>
I can execute the following in the callback function to set the datepicker on the two required inputs but that is causing weird things to happen with the datepicker such as the next button jumping from the year 2010 to 1900 and the previous button to jump to 1899.
$(".calendar").datepicker('destroy').datepicker({ dateFormat: 'dd/mm/yy', showAnim: 'fadeIn', duration: 200, gotoCurrent: true, changeYear: true, yearRange: 'c-120:c' });
As such I'd like to instead just confine the statement to the elements within the HTML snippet supplied to the callback function. What jQuery pattern can I use to acheive the following outcome noting that the html parameter is a string:
function SetCalendar(html) {
$("html.children .calendar").datepicker('destroy').datepicker({ dateFormat: 'dd/mm/yy', showAnim: 'fadeIn', duration: 200, gotoCurrent: true, changeYear: true, yearRange: 'c-120:c' });
}
You almost had it. If you use this as your ajax success function.
function ajaxSuccessFn(html) {
$(html).find('input.calendar').datepicker({
dateFormat: 'dd/mm/yy',
showAnim: 'fadeIn',
duration: 200,
gotoCurrent: true,
changeYear: true,
yearRange: 'c-120:c'
}).end().appendTo('#someElement');
}
There's probably a much better way but this works. I've still got the annoying issue where the next button on the datepicker jumps from July 2010 to January 1900 but I guess that's something else in the datepicker code.
function SetCalendar(html) {
var id = "#" + /.*?id="(.*?)"/.exec(html)[1];
$(id).find('input.calendar').datepicker('destroy').datepicker({
dateFormat: 'dd/mm/yy',
showAnim: 'fadeIn',
duration: 200,
gotoCurrent: true,
changeYear: true,
yearRange: 'c-120:c'
});
}
精彩评论