Trigger an event on `click` and `enter`

前端 未结 7 2089
醉话见心
醉话见心 2020-12-12 14:52

I have a searchbox on my site that. Currently, users must click the submit button next to the box to search via jquery\'s post. I would like to let users also press enter

相关标签:
7条回答
  • 2020-12-12 15:12

    Something like this will work

    $('#usersSearch').keypress(function(ev){
        if (ev.which === 13)
            $('#searchButton').click();
    });
    
    0 讨论(0)
  • 2020-12-12 15:13

    Use keypress event on usersSearch textbox and look for Enter button. If enter button is pressed then trigger the search button click event which will do the rest of work. Try this.

    $('document').ready(function(){
        $('#searchButton').click(function(){
            var search = $('#usersSearch').val();
            $.post('../searchusers.php',{search: search},function(response){
                $('#userSearchResultsTable').html(response);
            });
        })
        $('#usersSearch').keypress(function(e){
            if(e.which == 13){//Enter key pressed
                $('#searchButton').click();//Trigger search button click event
            }
        });
    
    });
    

    Demo

    0 讨论(0)
  • 2020-12-12 15:14

    You call both event listeners using .on() then use a if inside the function:

    $(function(){
      $('#searchButton').on('keypress click', function(e){
        var search = $('#usersSearch').val();
        if (e.which === 13 || e.type === 'click') {
          $.post('../searchusers.php', {search: search}, function (response) {
            $('#userSearchResultsTable').html(response);
          });
        }
      });
    });
    
    0 讨论(0)
  • 2020-12-12 15:20
    $('#form').keydown(function(e){
        if (e.keyCode === 13) { // If Enter key pressed
            $(this).trigger('submit');
        }
    });
    
    0 讨论(0)
  • 2020-12-12 15:24

    you can use below event of keypress on document load.

     $(document).keypress(function(e) {
                if(e.which == 13) {
                   yourfunction();
                }
            });
    

    Thanks

    0 讨论(0)
  • 2020-12-12 15:24

    Take a look at the keypress function.

    I believe the enter key is 13 so you would want something like:

    $('#searchButton').keypress(function(e){
        if(e.which == 13){  //Enter is key 13
            //Do something
        }
    });
    
    0 讨论(0)
提交回复
热议问题