简体   繁体   中英

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

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

Use

$("#search-input").data("source", suggestions);

because this

$("#search-input").attr("data-source", suggestions);

sets the attribute value (ie, a string) of data-source to the result of suggestions.toString() , which of course is

"value1,value2,value3"

FWIW, this would be correct as well, even though needlessly complicated:

$("#search-input").attr("data-source", JSON.stringify(suggestions) );

You can just use Split() method to create array

 suggestions.split(",");

 'value1, value2, value3'.split(","); // ["value1", " value2", " value3"]

一种快速可行的解决方案是

$("#search-input").attr("data-source", JSON.stringify(suggestions));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM