如何使用回车键触发搜索

时间:2015-02-02 19:49:40

标签: javascript jquery search keydown

我需要使用回车键触发搜索,但它不起作用,这是我使用的代码。任何帮助将不胜感激。

 $('#header input[name=\'search\']').bind('click', function(e) {

    if (e.keyCode == 13) {

        url = $('base').attr('href') + 'index.php?route=product/search';

        var search = $('input[name=\'search\']').attr('value');

        if (search) {
            url += '&search=' + encodeURIComponent(search);
        }

        location = url;
    }
});

2 个答案:

答案 0 :(得分:3)

你很可能想要抓住keyup事件而不是点击

 $('#header input[name=\'search\']').bind('keyup', function(e) {

    if (e.keyCode == 13) {
        console.log("FOOOOOO");
        url = $('base').attr('href') + 'index.php?route=product/search';

        var search = $('input[name=\'search\']').attr('value');

        if (search) {
            url += '&search=' + encodeURIComponent(search);
        }
        console.log("url: "+url);
        window.location.href  = url;
    }
});

我不知道你会尝试什么,但我会编码这个选择器:

$('#header input[name="search"]')...

已更新

// 
$('input[name="search"]').bind("enterKey",function(e){
   console.log("yeah i just triggered");
});


$('input[name="search"]').keyup(function(e){
    if(e.keyCode == 13)
    {
        $(this).trigger("enterKey");
    }
});

答案 1 :(得分:0)

如果可行,您最好使用

<input type="submit" value="">

将输入换行到<form>

和样式化按钮

input[type='submit'] {height: 0; width: 0; overflow: hidden;}

如果您需要在javascript中更改操作网址,请使用

之类的内容
$('form').submit ( function() {
    $(this).attr('action','/route-to-submit');
})
相关问题