0

How can I submit a pure inputs value using the enter key? I only have an input field like this and nothing more. The idea is to submit the value in it using ajax when a user hits enter.

<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();
    }
});

I'm having problems getting the thing to submit on enter and getting it's value. Can you please help?

4

3 回答 3

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
        });
    }
});
于 2013-11-05T14:47:42.337 回答
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();
});

小提琴:http: //jsfiddle.net/mSXk9/

于 2013-11-05T14:48:49.387 回答
0

请更准确地说..我不确定你想在那里做什么。但也许这对你有一点帮助:

<input onkeydown="if(event.keyCode==13){YourSearchFunction();return false;}">

keyCode 13 应该是“Enter”键。

于 2013-11-05T14:54:19.467 回答