Add And Remove Multiple Tag By Onclick To Textarea
I have a form with a textarea and list of tags from database( already queried and displayed under the textarea ) and want to add these tags (seperated by comma) on textarea and rem
Solution 1:
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/
Post a Comment for "Add And Remove Multiple Tag By Onclick To Textarea"