Easiest way to temporarily store key-value pairs in a form using JQuery

javascript, jquery

Solution

JQuery provides the `data` method for precisely these situations! It works directly with native JavaScript objects, so no need to mess about with comma separated lists - just use an array or object. Perhaps something like this will get you on the right track.

// initialize existing tags
$('#form').data('tags', { foo: true, bar: true });

// add a new tag
$('#form').data('tags').baz = true;

// remove an existing tag
$('#form').data('tags').bar = false;

$('#form').data('tags');
// { foo: true, bar: false, baz: true }

Having removed tags remain in the object as `false` will help you see which tags need unassigning server-side; not necessary but potentially useful to you.

If you would rather the removed values were removed completely from the object, use the `delete` construct.

// remove an existing tag
delete $('#form').data('tags').bar;

Edit: In an attempt to address your comments on this answer and give you some ideas:

<ul class="tags">
    <li>
        <span class="tag-name">foo</span>
        <a href="#" class="tag-remove">remove</a>
    </li>
</ul>

And your JavaScript:

$(function() {
    $('#form .tag-remove').click(function(e) {
        // update the tag data
        var tag = $(this).siblings('.tag-name').text();
        $('#form').data('tags')[tag] = false;

        // remove the tag element
        $(this).parent().remove();

        return false;
    });
});

There will be more of course - this does not handle the initialization of the form's tag data, the addition of new tags, or the submitting of tags to the server - but hopefully it will nudge you in the right direction :)

Problem

How can I temporarily store an array of string values most elegantly in a form? I have a form, where a user can edit an article - and add tags, which are simply string values. I don't want to persist it until the user actually saves the entire article, so I need to be able to temporarily ...: - Display the list of selected tags - Add a tag to the list - Remove a tag from the list - Submit the list of values when I save the form I could store everything in just a comma-separated hidden field, but it seems ugly, and I would prefer something stronger typed. What is the right way to do this? Pointers to examples very welcome.

Original source