0

using this little jquery i am able to save the data-id of the clicked list-element in an input-hidden-field:

(Important: Only one data-id can be saved in this input-hidden-field, if you click next element, this hidden-field gets updated.)

$(document).ready(function(){
    $('.ui-selectable :not([data-id=""])').click(function() {
        $('.ui-selectable .selected:not([data-id=""])').removeClass('selected');
        $(this).toggleClass('selected');
        $(this).parent().trigger('update');
    });

    $('.ui-selectable').on('update', function() {
        data = [];
        $(':not([data-id=""]).selected', this).each(function() {
            data.push( $(this).data('id') );
        });
    });
});

For now its saved in an array as you can see in:

data = [];

But i need to save it in a string, anybody could help with it?

1
  • Maybe call JSON.stringify on the array? Commented Dec 11, 2013 at 20:30

2 Answers 2

2

You can change that array into a string by using JSON.stringify,

Try this,

JSON.stringify(data);
Sign up to request clarification or add additional context in comments.

5 Comments

which line do i have to put it? after i declared the array?
@user3080627 This will convert the array data into a string. So you can call it after filling your array.
Some browsers don't support the JSON object. For more browser compatibility, you can just use the Array object's native toString() method. That is data.toString().
@TNguyen Can you name some of them.?
@RajaprabhuAravindasamy: lots, and not even that long ago! caniuse.com/#search=JSON
0

The join method will give you a comma separated string of your array.

1 Comment

This is a bad way to serialize arrays. If any strings within the array had a comma, you'd run into problems deserializing the string later. This is, of course, not always a problem if you know what type of data is in your array, but perhaps not the best habit to get into.

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.