Print a JavaScript array to HTML, square brackets and quotation marks intact
- by Mark Gia Bao Nguyen
I'd like to set the attribute of an input form with an array of values (to use for autocomplete search). I have a JS array that looks a little something like this:
var suggestions = ["value1", "value2", "value3"];
Using jQuery, I did this:
$("#search-input").attr("data-source", suggestions);
Desired output:
<input type='search' data-source='["value1", "value2", "value3"]' />
Actual output:
<input type='search' data-source='value1, value2, value3' />
This breaks the autocomplete as it requires an array (or at least something that looks like a JavaScript array).