Print a JavaScript array to HTML, square brackets and quotation marks intact

Posted by Mark Gia Bao Nguyen on Stack Overflow See other posts from Stack Overflow or by Mark Gia Bao Nguyen
Published on 2012-03-26T11:15:17Z Indexed on 2012/03/26 11:30 UTC
Read the original article Hit count: 263

Filed under:
|

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).

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html