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 ...:
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With