在“点击"和“输入"上触发事件 [英] Trigger an event on `click` and `enter`

查看:187
本文介绍了在“点击"和“输入"上触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有一个搜索框.当前,用户必须单击框旁边的提交"按钮才能通过jquery的帖子进行搜索.我想让用户也按Enter键进行搜索.我该怎么办?

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 to search. How can i do this?

JQUERY:

$('document').ready(function(){
    $('#searchButton').click(function(){
        var search = $('#usersSearch').val();
        $.post('../searchusers.php',{search: search},function(response){
            $('#userSearchResultsTable').html(response);
        });
    });
});

HTML:

<input type='text' id='usersSearch'  /><input type='button' id='searchButton' value='search' />

推荐答案

usersSearch文本框上使用keypress事件,然后查找 Enter 按钮.如果按下输入按钮,则触发搜索按钮单击事件,这将完成其余工作.试试这个.

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

这篇关于在“点击"和“输入"上触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆