简体   繁体   中英

How to catch an event when the user starts typing?

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, ie 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?

You can do it this way.

$("#textbox").keyup(function(){
    if($(this).val().length>0){
        $("#clearicon").show();
    }
    else
    {
         $("#clearicon").hide();
    }
});

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');
  }
});
$("#textbox").keydown(function(e){
   //  show "delete" icon
});
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();
   }
});

Hide icons by default

 $('#check').on('input', function() {
  if($(this).val() != '') {
    //Write show() function for icon selectors
  } else {
    // Write hide() function for icon selectors
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM