I have this code, which adds dynamic div right below the textbox but I want to remove it after the user deletes the characters:
The code below doesn’t work, I don’t see what I am doing wrong
See code below:
$(document).ready(function () {
$("#searchcontent").keypress(function (e) {
var dvSearch = $('<div />');
dvSearch.attr('dvSearch', '1');
if ($("#searchcontent").val().length >= 2) {
var pos = $(this).position();
dvSearch.html("<div>ffff:<div><div>eeee:<div><div>ggggg:<div>").css({
top: pos.top + $(this).height() + 18,
left: pos.left,
width: '300px',
position: 'absolute',
'background-color': 'Yellow'
}).insertAfter($(this));
}
else {
$("div[dvSearch='1']").remove();
}
});
});
I would suggest simply having a container ready to receive the result content in your HTML. Then you can reduce the problem by either adding the results there or emptying that container. In your original code, you were continually adding
divelements on everykeypressevent.Also, as others have mentioned, you will want to use
.keyup()instead of.keypress()to ensure the value of the input is correct when the event triggers.HTML
JS
jsfiddle