Reputation: 2310
I have a number of inputs on a page function as JQ UI datepicker. Each needs to have different settings. I want to minimize the JS so I save the settings as an attribute in each individual .
<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 load the options dynamically as the settings.
$(document).ready(function(){
$(".datepicker").each(function(index){
$(this).datepicker("option" , $(this).attr('options'));
});
});
datepicker is not functioning. If I empty the parentheses after $this.datepicker it works fine.
I have also tried another way to assign settings. ("option",...) no dice.
Upvotes: 3
Views: 4493
Reputation: 22194
Instead of using eval
(which is evil, btw) you can use $.parseJSON
like this:
$(this).datepicker( "option" , $.parseJSON( $(this).attr('options')) );
However, you should be careful to have valid JSON string.
Upvotes: 2
Reputation: 19251
essentially your are doing this:
$(document).ready(function(){
$(".datepicker").each(function(index){
$(this).datepicker("option" , "{ dateFormat: 'yy-mm-dd',changeYear: true,yearRange: '1920:2010'}" );
});
});
when you need to be doing either
$(document).ready(function(){
$(".datepicker").datepicker({ dateFormat: 'yy-mm-dd',changeYear: true,yearRange: '1920:2010'});
});
or this
$(document).ready(function(){
$(".datepicker").datepicker();
$(".datepicker").datepicker("option" , "dateFormat", 'yy-mm-dd');
$(".datepicker").datepicker("option" , "changeYear", true);
$(".datepicker").datepicker("option" , "yearRange", '1920:2010');
});
The first solution initiates the datepicker with a set of options, while the second solution initiates a datepicker, and then sets individual options. Your version was trying to be some hybrid of the two, and tried to use a string instead of an object literal encased in curly brackets.
Upvotes: 2
Reputation: 17955
Try this
$(this).datepicker(eval('(' + $(this).attr('options') + ')'));
Or use a json parser http://www.json.org/js.html
Upvotes: 2