jQuerys .autocomplete() function has two variants for it’s ‘source’ option.
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]
These both work fine when passed directly to the .autocomplete() function:
$('input').autocomplete({source: [ "Choice1", "Choice2" ], minLength: 0});
OR
$('input').autocomplete({source: [ { label: "Choice1", value: "value1" } ], minLength: 0});
BUT I can’t get either to work when passed as variables:
var source = '[ "Choice1", "Choice2" ]';
$('input').autocomplete({source: source, minLength: 0});
This is to do with implicit casting of the variable to a string – autocomplete treats the values from the variable identically to how it handles an AJAX source (which is a string).
Ultimately I want to use a JSON value from a data-json attribute of the input element.
For added interest:
$('input').autocomplete({source: $('input').data('json'), minLength: 0});
works perfectly for the first variant, but reverts to the string behavior for the second variant.
Using $('input').attr('data-json') doesn’t work for either variant.
A ‘hack’ which does work for both variants is to do this:
$('input').autocomplete({source: eval($('input').attr('data-json')), minLength: 0});
Did I miss something which would allow .data() to return the apparently valid JSON in the second variant as an object?
Is there another way, or do I just need to make peace with eval() despite all the wisdom around that it’s probably not a good thing to do?
Thanks for your thoughts..
That is a String, not an array.
Try without quotes:
If you find yourself in the situation of having to get the data from a JSON string, don’t use eval (it’s evil), use JSON.parse (which all modern browsers have)
or, since you are already using jQuery