JQuery UI datipaker options as variables

I have several inputs on a function page as a JQ UI datepicker. Each of them should have different settings. I want to minimize JS in order to keep the settings as an attribute for each.

<input type="text" class="datepicker" name="dateofbirth" id="dateofbirth" size="20" value="" options="{ dateFormat: 'yy-mm-dd',changeYear: true,yearRange: '1920:2010'}" />

<input type="text" class="datepicker" name="expdate" id="expdate" size="20" value="" options="{ yearRange: '2011:2020'}" />

I use js to dynamically load parameters as settings.

    $(document).ready(function(){
 $(".datepicker").each(function(index){
  $(this).datepicker("option" , $(this).attr('options'));
 });
});

datepicker does not work. If I omit the parentheses after $ this.datepicker, it works fine.

I also tried another way to assign settings. ("option", ...) no dice.

+3
source share
3 answers

try it

$(this).datepicker(eval('(' + $(this).attr('options') + ')'));

Or use the json parser http://www.json.org/js.html

+2
source

Essentially you do this:

$(document).ready(function(){
    $(".datepicker").each(function(index){
        $(this).datepicker("option" , "{ dateFormat: 'yy-mm-dd',changeYear: true,yearRange: '1920:2010'}" );
    });
});

when you need to do

$(document).ready(function(){
    $(".datepicker").datepicker({ dateFormat: 'yy-mm-dd',changeYear: true,yearRange: '1920:2010'});
});

or

$(document).ready(function(){
    $(".datepicker").datepicker();
    $(".datepicker").datepicker("option" , "dateFormat", 'yy-mm-dd');
    $(".datepicker").datepicker("option" , "changeYear", true);
    $(".datepicker").datepicker("option" , "yearRange", '1920:2010');
});

datepicker , datepicker, . , .

+2

Instead of using eval( which is evil , btw) you can use $.parseJSON:

$(this).datepicker( "option" , $.parseJSON( $(this).attr('options')) );

However, you must be careful to have a valid JSON string.

+2
source

Source: https://habr.com/ru/post/1783787/


All Articles