问题
I have multiple inputs
on my page, all of which have jQuery UI's datepicker widget attached to them.
What I would like to do is show/hide
the .ui-datepicker-calendar
based on a data-calendar
attribute on the input
element.
For example:
<input type="text" data-calendar="false" />
<input type="text" data-calendar="false" />
<input type="text" data-calendar="true" />
So, the first two should not show the .ui-datepicker-calendar
, but the last should.
I thought I could leverage the beforeShow
event to set the display of the element, however, at the time the event fires, the .ui-datepicker-calendar
does not yet exist:
$('input').datepicker({
beforeShow: function(el, dp) {
$('.ui-datepicker-calendar').toggle( !$(el).is('[data-calendar="false"]') );
}
});
I've had a look at similar questions, and the answer is to use CSS to hide the .ui-datepicker-calendar
element:
.ui-datepicker-calendar {
display: none;
}
However, this won't work for me as I need to set the display property based on the element's data-calendar
attribute.
Is there a simple way to achieve this? I had a look through the datepicker API but didn't come across anything.
Here's a simple base fiddle
Here's how I would like it to display, if data-calendar is false
回答1:
Having done some more searching, I came across this question which helped me solve my problem.
When the beforeShow
event fires, add/remove a class on the #ui-datepicker-div
element (this exists once the datepicker has been attached).
$('input').datepicker({
beforeShow: function(el, dp) {
$('#ui-datepicker-div').toggleClass('hide-calendar', $(el).is('[data-calendar="false"]'));
}
});
Then, just add a style for .ui-datepicker-calendar
within the .hide-calendar
class:
.hide-calendar .ui-datepicker-calendar {
display: none;
}
Here's a working fiddle
回答2:
Check the data attribute for each input element.
1) .data() - Method used to Store arbitrary data associated with the matched elements.
2) .each() - Method used to iterate objects of jQuery.
Try this.
$('input[type=text]').each(function(){
alert($(this).data('calendar'));
if($(this).data('calendar')){
$(this).datepicker();
}
});
Working Fiddle
From your comments,
$('input').datepicker();
$('input[type=text]').each(function () {
if ($(this).data('calendar')) {
$(this).datepicker();
}
else{
$(this).datepicker('destroy'); //Removes the datepicker functionality
}
});
Updated Fiddle
来源:https://stackoverflow.com/questions/18185163/hide-ui-datepicker-calendar-based-on-element-attribute