あなたの問題はこの行にあります
$('#tags').val(selectedTags.join(', '));
以前のものを上書きしていますtextarea
。
編集:
試してみてください:
http://jsfiddle.net/QyqYW/92/
var tags = [
'JavaScript',
'jQuery',
'HTML5',
'CSS3',
'PHP'
],
keys = "";
var selectedTags = [];
for(var i = 0; i < tags.length; i++) {
var el = $('<span>').text(tags[i]);
$('#tagButtons').append(el);
}
//changed click event to "on" event..
//it seems that click doesn't bind to dynamically added elements
$('#tagButtons').on("click" , "span" , function(){
//Checks if you've forgot to type "," and then adds your tag
if(keys != ""){
selectedTags.push(keys);
$('#debug').prepend($('<div>').html('Added: ' + keys));
var newEl = $('<span class="selected">').text(keys);
$('#tagButtons').append(newEl);
$('#tags').focus().val(selectedTags.join(', ') + ", ");
keys = "";
}
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));
$('#tags').focus().val(selectedTags.join(', ') + ", ");
} else {
selectedTags.push(val);
$(this).addClass('selected');
$('#debug').prepend($('<div>').html('Added: ' + val));
$('#tags').focus().val(selectedTags.join(', ') + ", ");
}
});
//adds tag after you type ","..
//if you forgot to, look above the first line in the on event
$("#tags").keydown(function(evt){
if(evt.which == 188){
selectedTags.push(keys);
$('#debug').prepend($('<div>').html('Added: ' + keys));
var newEl = $('<span class="selected">').text(keys);
$('#tagButtons').append(newEl);
$('#tags').val(selectedTags.join(', '));
keys = "";
} else if(evt.which ==8){
//for after adding tag you can't use Backspace to delete it.
//remove tag from butotns
if(keys == ""){
evt.preventDefault();
} else {
keys += String.fromCharCode(evt.which).toLowerCase();
}
});