Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery datepicker - override options from data-attribute

I'm using this markup

<label> Date <input type="text" data-datepicker="{maxDate: '+1d'}" /></label>
<label> Another date <input type="text" data-datepicker="" /></label>
<script>
$('[data-datepicker]').each(function() {
      // init the options var with some default values (dateFormat etc)
      // that can be overridden by the data-datepicker values
      // also, new values can be added to the options from data-datepicker
      // such as in the above example "maxDate"
      var options = TODO;      

      $(this).datepicker(options);
});
</script>

I don't really know where to start with that options object.. Starting with the default values seems like a good start

var options = { dateFormat: 'yy-mm-dd }; 

But then how I add/overwrite with values from the data-attribute .. I just don't know

like image 247
Ivar Avatar asked Nov 29 '11 08:11

Ivar


1 Answers

With this markup (you must format the "data" attribute like this so that they are recognized as objects):

<label> Date <input type="text" data-datepicker='{"maxDate": "+1d"}' /></label>
<label> Another date <input type="text" data-datepicker='{ "dateFormat": "dd-mm-yy"}' /></label>

You could do:

$('[data-datepicker]').each(function() {
    //standard options
    var options = { dateFormat: "yy-mm-dd"};   
    //additional options
     var additionalOptions = $(this).data("datepicker");
    //merge the additional options into the standard options and override defaults
    jQuery.extend(options, additionalOptions);


      $(this).datepicker(options);
});

fiddle here: http://jsfiddle.net/WrRte/

like image 188
Nicola Peluchetti Avatar answered Nov 10 '22 11:11

Nicola Peluchetti