Deleting entry in input
This is my code:
$('#enterTags').keydown(function(event) {
var tag = $(this).val();
// 18开发者_运维问答8 is comma, 13 is enter
if (event.which === 188 || event.which === 13) {
if (tag) {
$('#falseInput').val($('#falseInput').val() + tag + ', ');
$(this).val('');
}
event.preventDefault();
}
// 8 is backspace
else if (event.which == 8) {
if (!tag) {
event.preventDefault();
}
}
});
The problem I am having now is when a user presses backspace, I need it to clear #falseInput of the most recent "tag" var I entered in #enterTags. How can I do this?
You can store the tags in an array and set the value of #falseInput
by joining the elements of the array (join
method). Then, when the user presses backspace, just remove the last element of the array. This approach will be easier than trying to manipulate the string stored in the input.
You can just keep each completed tag in a stack by doing tagsArray.push(tag);
. You can display the array by doing $('#falseInput').val(tagsArray.join(', '));
When the backspace is pressed, all you need to do is
tagsArray.pop();
$('#falseInput').val(tagsArray.join(', '));
That removes the most recent value from the array then redoes the value of #falseInput
精彩评论