The easiest way to temporarily store key-value pairs in a form using jQuery

How to temporarily store an array of string values ​​most elegantly in a form?

I have a form where the user can edit the article - and add tags that are just string values.

I do not want to insist on it until the user saves the entire article, so I need to be able to temporarily ...:

  • Display a list of selected tags
  • Add tag to list
  • Remove tag from list
  • Submit list of values ​​when saving form

I could only store everything in a hidden field, separated by commas, but it seems ugly, and I would prefer something stronger.

What is the right way to do this? Pointers to examples are very welcome.

+4
source share
1 answer

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

+8
source

All Articles