用户使用jQuery在输入框上输入(使用键盘)时如何调用ajax() [英] How do I call ajax() when user enter(using keyboard) on input box using jquery
问题描述
当用户在输入框没有页面加载的情况下输入时,我试图调用ajax(),但是当用户在输入框上键入内容时,它正在调用此ajax方法.我的输入框如下:
I'm trying to call ajax() when users enter on input box without page load but it's calling this ajax method when users typing on input box. My input box is following :
<input type="text" name="search" id="txt_name" placeholder="Keyword"/>
Jquery./Ajax Code;
$(document).ready(function(){
$("#txt_name").keyup(function(){
var value = $('#txt_name').val();
$.ajax({
type:"post",
url:"doSearchEnter.php",
data :{
'key' : value
},
success:function(res){
$('#showSearchResult').html(res);
}
});
});
});
在用户在没有页面加载的输入框上输入后,如何称呼我为ajax()?
How do I call I this ajax() after user enter on input box without page load ?
更新:
$('#txt_name').on('click', 'submit', function(e) {
e.preventDefault();
$.ajax({
type:"post",
url:"doSearchEnter.php",
data :{
'key' : value
},
success:function(res){
$('#showSearchResult').html(res);
}
});
});
更新2:
<form>
<input type="button" name="given_name" value="Given Name" class="search_submit" id="given_name"/>
<input type="button" name="company_name" value="Company Name" class="search_submit" id="company_name"/>
<input type="button" name="cdid" value="ID" class="search_submit" id="cdid"/>
<input type="text" name="search" id="txt_name" placeholder="Keyword"/>
</form>
$('form').on('click', 'submit', function(e){
e.preventDefault();
});
$('form').on('keyup', '#txt_name', function(e){
if(e.keyCode == '13'){
$.ajax({
type:"post",
url:"doSearchEnter.php",
data :{
'key' : value
},
success:function(res){
$('#showSearchResult').html(res);
}
});
}
});
推荐答案
使用提交按钮将表单中的输入放置在表单中应该可以解决问题.当用户按Enter键时,表格应提交.您所要做的就是使用
Placing the input inside of a form with a submit button should do the trick. When the user presses enter the form should submit. All you have to do is use
$('form').on('click', 'submit', function(e) {
e.preventDefault();
$.ajax({
//do your Ajax thing here
});
});
更新: 对于三种形式,您将对所有三种形式使用相同的Ajax调用,然后将数据放在一起.
UPDATE: For three forms you would use the same Ajax call for all three and put your data together like so.
var formData = $(this).closest('form').serialize();
$.ajax({
type: 'POST',
url: 'test.php',
data: formData
});
这将告诉jquery将表单数据以适当的格式放置,以传递给服务器端脚本,并且适用于所有三个脚本
This would tell jquery to put the forms data in a proper format for passing to your server side script and would work for all three scripts
UPDATE2: 根据更新的问题进行更新:
UPDATE2: UPDATE BASED ON UPDATED QUESTION:
$('form').on('submit', function(e){
e.preventDefault();
});
$('form').on('keyup', '#txt_name', function(e){
if(e.keyCode == '13'){
$.ajax({
//do Ajax stuff
});
}
});
这是工作代码的链接! jsfiddle
here is link to the working code! jsfiddle
这篇关于用户使用jQuery在输入框上输入(使用键盘)时如何调用ajax()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!