3
var arr=[...];

var html = '<input attr="' + serialize(arr) + '">';

I can't simply join(' ') the arr as there may be white space or other special characters.

How do I do it properly?

0

2 Answers 2

2

You probably want .data, using which you can store any data on a DOM element.

var html = $("<input>");
html.data("something", arr);

Then you can append it somewhere using the insertion methods like .append.

Fetch the data again with:

var arr = html.data("something");

http://jsfiddle.net/UKRcs/


An alternative would be using JSON to convert things into a string and setting that as an attribute:

var html = $("<input>").attr("data-something", JSON.stringify(arr));

And the other way round:

var arr = JSON.parse(html.attr("data-something"));

http://jsfiddle.net/UKRcs/1/

Sign up to request clarification or add additional context in comments.

7 Comments

@Je Rog: Can't you use the jQuery functions? If you can, you really ought to, because .data is by far the most convenient way of storing data on an element.
Lots of other code requires to generate html string, so I have to make it compatible with those...
@Je Rog: That's trickier but certainly possible - see my edit please.
Do you mean '<input attr="' + JSON.stringify(arr) + '" />'? This may break DOM because of ' and "...
@Je Rog: Yes, if you really want a direct string that's the way to for arrays. (Keep in mind that objects would have " around their keys so that would break up with the attribute ".)
|
1

You may want to look at the .data() method. This allows you to attach arbitrary objects to DOM elements.

http://api.jquery.com/data/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.