Trigger an event on `click` and `enter`

前端 未结 7 2103
醉话见心
醉话见心 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: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);
          });
        }
      });
    });
    

提交回复
热议问题