开发者

trouble catching enter keystroke in javascript

开发者 https://www.devze.com 2023-03-26 16:55 出处:网络
this seems simple, but i can\'t make it work. i\'m trying to catch an enter keystroke, and run some code, but when i hit enter, the page refreshes and nothing happens.

this seems simple, but i can't make it work.

i'm trying to catch an enter keystroke, and run some code, but when i hit enter, the page refreshes and nothing happens.

here's my script

function GetChar(event) {
    var keyCode = ('which' in event) ? event.which : event.keyCode;
    if (keyCode == '13') {
        var cQuery = document.getElementById('searchfield').value;
        var cURL = 'ProductGrid.aspx?Query=' + escape(cQuery);
        document.location = cURL;
    };

whe开发者_运维知识库ni hit enter the page is refreshed, and the search field is cleared, but it doesn't run any of the code in the if block


If your searchfield is inside a Form, this Form gets submitted, causing your code not to run.

You can either remove the Form and just use the Input-field, or you have to stop the Form-Submit by using somehting like this:

<form onSubmit="this.preventDefault&&this.preventDefault();this.returnValue=false;return false;">


Are you using keypress event? Explorer doesn't fire the keypress event for Enter...

http://www.quirksmode.org/js/keys.html


Returning false from your function could do the job.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号