Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

javascript - 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 remove if the tag is already there as user click on them.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...