When you call data
function, it returns string so you have to convert it to an object and then pass it to datepicker
and remove curly bracket from value of data-options
.
Solutions:
1- Use eval
Javascript
eval('({' + $(this).data('options') + '})')
HTML
data-options="maxDate:'0'"
2- Jquery .data
and surround your data attribute value by '
Javascript
$(this).data('options')
HTML
data-options='{"maxDate":0}'
3- use plugin or write custom function(the below code is written by @allenhwkim).
Javascript
function JSONize(str) {
return str
// wrap keys without quote with valid double quote
.replace(/([\$\w]+)\s*:/g, function(_, $1){return '"'+$1+'":'})
// replacing single quote wrapped ones to double quote
.replace(/'([^']+)'/g, function(_, $1){return '"'+$1+'"'})
}
jQuery.parseJSON(JSONize($(this).data('options')));
HTML
data-options="{maxDate:'0'}"
Note: all above solutions are tested and they works.
$("input.dataWithoutOptions").each(function() {
$(this).datepicker({
maxDate: '0'
})
});
$("input.data").each(function() {
var dateOptions = eval('({' + $(this).data('options') + '})');
console.log(typeof($(this).data('options'))); //String
console.log(typeof(dateOptions)); //Object
$(this).datepicker(dateOptions)
});
input {
display: block;
margin: 10px 0 20px;
padding: 5px;
}
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
This has options attr:
<input class="data" type="text" data-options="maxDate:'0'" />This is just a date pick:
<input class="dataWithoutOptions" type="text" />
Jsfiddle