简体   繁体   中英

.NET Submit Fires Before Javascript onKeypress

I am trying to use onkeypress on an input type="text" control to fire off some javascript if the enter button is pressed. It works on most pages, but I also have some pages with custom .NET controls.

The problem is that the .NET submit fires before the onkeypress. Does anybody have an insight on how to make onkeypress fire first?

If it helps, here is my javascript:

 function SearchSiteSubmit(myfield, e)
{
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;
    else 
        return true;
    if (keycode == 13)
    {
        SearchSite();
        return false;
    }
    else 
        return true;
}

Javascript OnKeyPress will always fire first, it's more a case of wether or not it has completed its operation before the page is posted back..

I would say rethink what is going on and where.. What is taking place at the server side?

This isn't a very clear question so I'll give it a shot --

It looks like you're looking for a keypress of "enter" here. The problem seems to be that the "enter" key is usually bound to the submit button on a form automatically by the browser, which means that when the user presses enter, you submit the form, rather than running the javascript you have here. What you should do is make a global event handler that checks to see if "MyField" has the focus when the enter button is pressed, and if so, then fire the javascript, rather than submitting the form. I Hope I understood your question!

How are you assigning the javascript?

It should look like:

<input id="TextID" type="text" onkeypress="return SearchSiteSubmit('TextID', event)" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM