1

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

3 Answers 3

3

Use

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

because this

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

sets the attribute value (i.e., 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) );
Sign up to request clarification or add additional context in comments.

Comments

2

You can just use Split() method to create array

 suggestions.split(",");

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

Comments

1

One quick possible solution is

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.