简体   繁体   中英

how to make keyboard shortcut with key “c” from keyboard for calling a function

I am wondering if it is possible to call a jquery function from keyboard key.

Say i want to clear textbox values , if users press "c" key from her keyboard.

Now i am calling a function onclick event.Same function i want to call if users press "c" key from keyboard

  $(".clear").click(function()
        { 
            $('#from_amount').val(''); 
            $('#to_amount').val(''); 
            $('.clear').hide(); 
        });

Please help me to solve this problem

Use the keypress event to handle this.

One possible problem with this will be, you won't be able to press c anywhere in the document, so you may want to support a key combination like ctrl + c . Or do not want to do this when the key is pressed within a input field

<script>
    $(function(){
        $(document).keypress(function(e){
            if(e.which == 99){
                    $('#from_amount').val(''); 
                    $('#to_amount').val(''); 
                    $('.clear').hide(); 
            }
        })
    })
</script>

Ignoring keypress from input fields

<script>
    $(function(){
        $(document).keypress(function(e){
            if(e.which==99 && !$(e.target).is(':input')){
                console.log('clear')
            }
        })
    })
</script>

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