How to get enter key to trigger button click event/postback

Discussion in 'ASP .Net Web Controls' started by Yuval Kordov, Jan 7, 2004.

  1. Yuval Kordov

    Yuval Kordov Guest

    Hi there. First post. I've been investigating a problem
    for many days now and have been frustrated at every turn.

    Situation: An page (C#) with two textbox
    controls, each of which I'd like to tie to a different
    imagebutton control (normal button controls are not an
    option.) So, imagine the following controls:


    Hitting enter while in txtKeyword should fire a click
    event on btnSearch. Hitting enter while in txtUserName
    should fire a click event on btnLogin.

    This is easy to do in Internet Explorer. But I have had
    zero success getting it to work in Netscape (7) and

    I have basically created two javascript functions: one
    that finds the desired button control and another that
    clicks it. The code I am using follows:


    function FindButton(controlId)
    if (document.getElementById) {
    var el1 = document.getElementById(controlId);
    if (el1 != null)
    return el1;

    if (document.all)
    var el2 = document.all[controlId];
    if (el2 != null)
    return el2;

    var frm = document.forms[0];
    var el3 = frm.controlId;
    if (el3 != null)
    return el3;

    for (var i = 0; i < frm.elements.length; i++) {
    if ( != -1) {
    return frm.elements;

    return null;

    function enterKeyTrap(e, controlId)
    if ((e.which && e.which == 13) || (e.which && e.which
    == 3) ||
    (e.keyCode && e.keyCode == 13) || (e.keyCode &&
    e.keyCode == 3))
    var xcontrol = FindButton(controlId);
    if (xcontrol != null)
    if (e != null)
    e.cancelBubble = true;
    e.returnValue = false;
    return false;
    return true;

    Code-behind, attributes being added:

    enterKeyTrap(event,'" + btnSearch.ClientID+ "');");
    enterKeyTrap(event,'" + btnLogin.ClientID+ "');");

    As I said, I have searched far and wide but have not
    found anything that is cross-browser that works. Netscape
    and Safari always either fire the default button (the
    first one that renders) or do nothing at all. I would
    appreciate any help with this as it's driving me up the
    wall. After developing in .net for two years, I still
    find it hard to believe that there is no built-in
    facility for enter key handling.
    Yuval Kordov, Jan 7, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.