JQuery provides a data method specifically for these situations! It works directly with native JavaScript objects, so there is no need to be confused with comma-separated lists - just use an array or object. Perhaps something like this will get you back 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 }
Removing tags remains in the object, since false helps you see which tags need to be assigned a name to the server side; not necessarily, but potentially useful to you.
If you prefer deleted values ββto be completely removed from the object, use the delete construct.
// remove an existing tag delete $('#form').data('tags').bar;
Edit: in an attempt to answer your comments on this 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 initializing the form tag data, adding new tags or sending tags to the server - but I hope it pushes you in the right direction :)
source share