I think I know what you mean, please have a look at this fiddle
http://jsfiddle.net/joevallender/QyqYW/1/
The code is below. tags
would come from the server and selectedTags
is the managed array of current selections. you could load data from the server into selectedTags
too if necessary, if for instance editing an existing tagged post. If you did this, you’d refactor the code in the click()
function out to its own function so it could be run on document ready too.
I’ve included some class toggling and a debug screen so you can see what is going on.
HTML
<textarea id="tags"></textarea>
<div id="tagButtons"></div>
<div id="debug"></div>
and JavaScript
var tags = [
'JavaScript',
'jQuery',
'HTML5',
'CSS3'
];
var selectedTags = [];
for(var i = 0; i < tags.length; i++) {
var el = $('<span>').text(tags[i]);
$('#tagButtons').append(el);
}
$('#tagButtons span').click(function(){
var val = $(this).text();
var index = selectedTags.indexOf(val);
if(index > -1) {
var removed = selectedTags.splice(index,1);
$(this).removeClass('selected');
$('#debug').prepend($('<div>').html('Removed: ' + removed));
} else {
selectedTags.push(val);
$(this).addClass('selected');
$('#debug').prepend($('<div>').html('Added: ' + val));
}
$('#tags').val(selectedTags.join(', '));
});
EDIT Here is one that works in both directions http://jsfiddle.net/joevallender/QyqYW/14/
6
solved add and remove multiple tag by onclick to textarea