如何使用回车键提交纯输入值?我只有这样的输入字段,仅此而已。我们的想法是在用户点击进入时使用ajax提交其中的值。
<input class="input-xxlarge search" type="search" name="search" value="" autocomplete="off" placeholder="Search for recipes">
$('.search').submit(function(event){
console.log('Ok');
var $this = $(this);
var query = $this.('.search').val();
if(query.length >= 2 || query.lenght <=24) {
console.log(query);
} else {
// Do not submit the form
event.preventDefault();
}
});
我在输入并提供它的价值时遇到问题。你能帮忙吗?
答案 0 :(得分:3)
表单有submit
个事件,输入没有。请改用keyup
事件来触发您的AJAX请求:
$('.search').on('keyup', function(e) {
if(e.which === 13) {
// enter key pressed
var value = this.value; // this is the inputs value
$.ajax({
url: 'your-url',
data: {
search: value
},
// more options
}).done(function(response) {
// do something with the response
});
}
});
答案 1 :(得分:2)
你有什么理由不能使用表格吗?
我建议你把它放在一个并将提交事件附加到它而不是你的输入。
<form action="#" id="your-form">
<input class="input-xxlarge search" type="search" name="search" value="" autocomplete="off" placeholder="Search for recipes">
</form>
JavaScript的:
$('#your-form').submit(function(e) {
var val = $('.search').val();
/* your code here */
e.preventDefault();
});
答案 2 :(得分:0)
请更确切地说..我不确定你想在那里做什么。 但也许这会对你有所帮助:
<input onkeydown="if(event.keyCode==13){YourSearchFunction();return false;}">
keyCode 13应为“Enter”键。