输入/按键上的jQuery不起作用 [英] Jquery on enter/keypress not working
问题描述
我正在尝试创建一个简单的搜索框,该框允许您根据您在输入字段中输入的关键字进行搜索.如果按提交"按钮,则此工作正常.
I'm trying to create a simple search box that allows you to search based on a keyword you enter in the input field. This work fine if you press the Submit button.
我还希望能够按Enter或Return键来启动搜索.我试过使用.on函数,它似乎只对单击有效,但在enter或keypress上没有成功. 任何见识将不胜感激!
I would also like to be able to press the Enter or Return key to initiate the search. I've tried using the .on function it only seems to work for click but no success on enter or keypress. Any insight would be greatly appreciate!
$(document).ready(function() {
//$("#gallery").empty();
$("#submit").on("click keypress",function (e) {
console.log( $( this ).text() );
console.log("e.which " +e.which);
console.log("e.type " +e.type);
if (e.which === 13 || e.type === 'click') {
if($("#term").val() !="" ){
//$("#gallery").empty();
/**********************/
updatestatus();
ajaxProcess();
/**************************/
}else {
//$("#gallery").text("Please enter a keyword to search").fadeOut(2500);
alert("Please enter a keyword to search");
}
}
});
$("#clear").click(function(){
$("#gallery").empty();
});
});
HTML
<form>
<input type="text" value="" id="term" />
<input id="submit" type="button" value="Go">
<input type="reset" id="clear" value="Clear" />
</form>
推荐答案
将onsubmit
事件处理程序绑定到表单.因此,当您单击输入文本中的enter
键时,表单提交将触发并执行您的ajax调用.
Bind a onsubmit
event handler to the form. So when you click on enter
key in the input text, the form submit will trigger which will execute your ajax call.
$("#submit").on("click keypress",function (e) {
if($("#term").val() !="" ){
/*
updatestatus();
ajaxProcess();
*/
}else {
alert("Please enter a keyword to search");
}
});
$("#clear").click(function(){
$("#gallery").empty();
});
$("form").submit(function(e){
$("#submit").trigger('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" value="" id="term" />
<input id="submit" type="button" value="Go">
<input type="reset" id="clear" value="Clear" />
</form>
或将keypress
事件绑定到input
文本框,并检查event.which==13
以检查其回车键并执行该过程.
Or bind keypress
event to the input
text box and check for event.which==13
to check if its enter key and do the process.
$("#submit").on("click keypress",function (e) {
if($("#term").val() !="" ){
/*
updatestatus();
ajaxProcess();
*/
}else {
alert("Please enter a keyword to search");
}
});
$("#clear").click(function(){
$("#gallery").empty();
});
$("input#term").on("keypress", function(e){
if (e.which === 13) {
$("#submit").trigger('click');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" value="" id="term" />
<input id="submit" type="button" value="Go">
<input type="reset" id="clear" value="Clear" />
</form>
这篇关于输入/按键上的jQuery不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!