javascript - Enter in search box and redirect to another page - Stack Overflow

admin2025-04-19  0

// catch enter code in search form in front page
$('#search').keypress(function (e) {
    var str = $('#search').val();
    var url = "default.aspx?search=" + str;
    if (e.keyCode == 13) {
        location.href = url;
    }
});

I don't know why this code doesn't work what I expected " When you enter something in input#search, check if it's not empty then redirect to another page ". I try to enter every line in console without checking event, it works!

How can I fix this and why it doesn't work ? Thanks for your consideration time :)

// catch enter code in search form in front page
$('#search').keypress(function (e) {
    var str = $('#search').val();
    var url = "default.aspx?search=" + str;
    if (e.keyCode == 13) {
        location.href = url;
    }
});

I don't know why this code doesn't work what I expected " When you enter something in input#search, check if it's not empty then redirect to another page ". I try to enter every line in console without checking event, it works!

How can I fix this and why it doesn't work ? Thanks for your consideration time :)

Share edited Dec 12, 2011 at 2:17 Christian 19.8k3 gold badges57 silver badges70 bronze badges asked Dec 12, 2011 at 2:15 Tzu ngTzu ng 9,25414 gold badges68 silver badges106 bronze badges 3
  • There's nothing wrong with that code (see: jsFiddle). Can you provide an example where it doesn't work? – Christian Commented Dec 12, 2011 at 2:21
  • I don't know why it doesn't work but replacing keyup with keypress, it works now :) – Tzu ng Commented Dec 12, 2011 at 2:35
  • Hei! I know this is an old question, but I am stuck and would really appreciate if you could help me out! My question: stackoverflow./questions/31700239/… – Kristine Commented Jul 30, 2015 at 6:47
Add a ment  | 

2 Answers 2

Reset to default 2

You might try .keyup() instead of .keypress(). Keypress is not an official specification, and can have unfortunate consequences in some browsers.

Put your domain including http for location href to work correctly

    // catch enter code in search form in front page
$('#search').keypress(function (e) {
    var str = $('#search').val();
    var domain = "http://www.yourdomain.";
    var url = domain+"default.aspx?search=" + str;
    if (e.keyCode == 13) {
        location.href = url;
    }
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745057951a282517.html

最新回复(0)