How To Check/remove An Element?
I want to remove a tag either by pressing backspace button (when the input is focused) or by clicking on that tag. Now I'm talking about the first option. Also I need to set it a
Solution 1:
You'd have better to toggle a class and check for it, e.g:
$(function() {
$("#tags input").on({
focusout: function() {
var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig, ''); // allowed charactersif (txt) $("<span/>", {
text: txt.toLowerCase(),
insertBefore: this
});
this.value = "";
},
keyup: function(ev) {
// if: comma|enter (delimit more keyCodes with | pipe)if (/(188|13|32)/.test(ev.which)) {
$(this).focusout();
} elseif (/(8)/.test(ev.which) && this.value == '' && $(this).prev("span").hasClass('toRemove')) { //<< check for class
$(this).prev("span").remove();
} elseif (/(8)/.test(ev.which) && this.value == '') {
$(this).prev("span").addClass('toRemove'); //<< add class
} else {
$(this).prevAll('.toRemove').removeClass('toRemove'); //<< remove class on keyup
}
}
});
$('#tags').on('click', 'span', function() {
$(this).remove();
});
});
#tags {
float: right;
border: 1px solid #ccc;
padding: 5px;
font-family: Arial;
}
#tags > span {
cursor: pointer;
display: block;
float: right;
color: #3e6d8e;
background: #E1ECF4;
padding: 5px;
padding-right: 25px;
margin: 4px;
}
#tags > span:hover {
opacity: 0.7;
}
#tags > span:after {
position: absolute;
content: "×";
border: 1px solid;
padding: 2px5px;
margin-left: 3px;
font-size: 11px;
}
#tags > input {
direction: rtl;
background: #eee;
border: 0;
margin: 4px;
padding: 7px;
width: auto;
}
.autocomplete {
display: none;
}
#tags > span.toRemove {
background-color: red;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divid="tags"><span>php</span><span>html</span><inputtype="text"value=""placeholder="Add a tag" /><divclass="autocomplete"></div></div>
Solution 2:
I built in a counter for you that checks the status of your keypress. If you press once the counter is 1 and if you press the second time it removes the element and is 0 again. I hope thats what you wanted. Check this:
$(function() {
counter = 0;
$("#tags input").on({
focusout: function() {
var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig, ''); // allowed charactersif (txt) $("<span/>", {
text: txt.toLowerCase(),
insertBefore: this
});
this.value = "";
$("#tags span").css('background-color', '#E1ECF4');
counter = 0;
},
keyup: function(ev) {
// if: comma|enter (delimit more keyCodes with | pipe)if (/(188|13|32)/.test(ev.which)) {
$(this).focusout();
} elseif (/(8)/.test(ev.which) && this.value == '') {
counter = counter + 1;
if (counter == 1) {
$(this).prev("span").css('background-color', 'Red');
} else {
$(this).prev("span").remove();
counter = 0;
}
}
}
});
$('#tags').on('click', 'span', function() {
$(this).remove();
$("#tags span").css('background-color', '#E1ECF4');
counter = 0;
});
});
Post a Comment for "How To Check/remove An Element?"