简体   繁体   中英

Javascript detect allow only one click and keyup on input

I have the following code in order to show a message when a specific input has been clicked or selected with the tab button. Now I want to show the message only when the input is clicked for the first time or when the input is selected for the first time. How can I implement the one click only and one keyup only?

 $("#field").on( 'keyup', function( e ) { if( e.which == 9 ) { alert("test keyup") } } ); $("#field").click(function() { alert("test click"); });
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="field" name="field_name" type="text" />

You can use off() once the message display as below.

Also you can use one() instead of on

 $("#field").on( 'keyup', function( e ) { if( e.which == 9 ) { alert("test keyup") $( this ).off( e ); } } ); $("#field").click(function(e) { alert("test click"); $( this ).off( e ); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="field" name="field_name" type="text" />

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