Reputation: 2863
I have an input box with an inline cross icon. The job of that icon is to clear the input box when clicked. This is what it looks like:
Now, having this icon visible when there's no text in the input box as shown in the picture doesn't make any sense. Ideally, the right thing to do would be to keep it hidden and show it only once the user starts typing something inside of the box. How do I catch that particular event (of the user starting to type)? I am aware of oninput()
but the problem is, it fires every time anything is typed. So if you type, say, "wiki," it will fire 4 times! I need something that fires only once when you type the first letter. Is it even possible?
Another alternative I can think of is to have a function watch the input box value and fire up the moment it's no longer empty. Something like this:
var check = document.getElementById('word').value;
if(check != ""){
// show "delete" icon
}
But in this case, how can I ensure the function does trigger, i.e. it's always on the lookout for the input box value change? Would it help to place the above snippet inside an anonymous function and leave it at that?
Upvotes: 2
Views: 4907
Reputation: 2854
Hide icons by default
$('#check').on('input', function() {
if($(this).val() != '') {
//Write show() function for icon selectors
} else {
// Write hide() function for icon selectors
}
});
Upvotes: 2
Reputation: 3760
You can do it this way.
$("#textbox").keyup(function(){
if($(this).val().length>0){
$("#clearicon").show();
}
else
{
$("#clearicon").hide();
}
});
Upvotes: 3
Reputation: 65
You can use keydown event and check value of input every time whether it is empty or not if its value is empty then hide the delete icon else show it.
$("#textbox").keydown(function(e){
if($("textbox").val()==null || $("textbox").val()=="")
{
$("deleteIcon").hide();
}
});
Upvotes: 1
Reputation: 637
You should not fire it just once because otherwise if the user deletes the content of the input text you would still be showing the button. Instead you can do:
document.getElementById('itext').addEventListener('input', function(e) {
if (e.target.value !== '') {
console.log('show button');
}
else {
console.log('hide button');
}
});
Upvotes: 2