How to add a custom class to my JQuery UI Datepicker

前端 未结 4 2000
鱼传尺愫
鱼传尺愫 2020-12-10 11:24

I have several inputs which trigger JQuery UI datepickers e.g.





        
4条回答
  •  失恋的感觉
    2020-12-10 12:04

    beforeShow can be used to manipulate the class before showing the datepicker.

    $('input').datepicker({
       beforeShow: function(input, inst) {
           $('#ui-datepicker-div').removeClass(function() {
               return $('input').get(0).id; 
           });
           $('#ui-datepicker-div').addClass(this.id);
       }
    });
    

    Demo (using jQuery 1.6.2 but needs jQuery > v1.4 for the .removeClass() which takes a function)

    Note This works by removing all the classes (i.e. ids) with a **general $('input') selector which you might want to limit to just pick up the elements that have been modified into date pickers.

    Edit Just had an upvote for this and looking at the code, it did not seem to do what I explained it should (maybe I misunderstood the question!). So, here is a version which adds a class equal to the id of the clicked on to the datepicker. Also uses the original .removeClass() so this will work with jQuery > v1.2.

    var inputIds = $('input').map(function() {
        return this.id;
    }).get().join(' '); // space separated ready for removeClass
    
    $('input').datepicker({
       beforeShow: function(input, inst) {
           $('#ui-datepicker-div').removeClass(inputIds);
           $('#ui-datepicker-div').addClass(this.id);
       }
    });​
    

提交回复
热议问题