• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 17615
  • Last Modified:

How to capture tab or enter key stroke?

Hello experts, I have a javascript function that fires when a user enters a key into a textfield.  I want to be able to execute some script when either enter or tab is pressed and it doesnt work.  When I hit enter it submits the form because I have buttons on the web page and when I hit tab it just jumps to the next text field.  Could someone look at the code and modify it to accept enter or tab?

      <script language="javascript">
            function checkname(oTextbox)
            {
            oTextbox.focus;
            var val = window.event.keyCode;
            alert(val);
            if(val == 8 || val == 46){
            //Do nothing if backspace or delete is pressed
            }
            else
            {
            var temparray
            this.textbox = oTextbox
            var temptext = oTextbox.value.length
if ( // i need to check for tab or enter here){
            var textval = check_name(oTextbox.value)
      temparray =  check_fields(oTextbox.value).split("/")
             document.getElementById('txtfirstname').value = temparray[0]
             document.getElementById('txtm').value = temparray[1]
              document.getElementById('txtareacode').value = temparray[2]
               document.getElementById('txtprefix').value = temparray[3]
               document.getElementById('txtsuffix').value = temparray[4]
            oTextbox.value += textval
            var oRange = oTextbox.createTextRange();
oRange.moveStart("character", temptext);
oRange.moveEnd("character",  oTextbox.value.length - textval.length);
oRange.select();
oTextbox.focus();
}
  }
            }
            </script>
0
tentavarious
Asked:
tentavarious
1 Solution
 
rama_krishna580Commented:
Hi,

try this....

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Tab with Enter Key</title>
    <script type="text/javascript">      
      // xBroswer event subscription
      function addListener(a,b,c,d){if(a.addEventListener){a.addEventListener(b,c,d);return true;}else if(a.attachEvent){var e=a.attachEvent("on"+b,c);return e;}else{alert("Handler could not be attached");}}
      function bind(a,b,c,d){return window.addListener(a,b,function(){d.apply(c,arguments)});}
      //
 
      // Generic dispatcher for keystrokes
      function handleKeystroke(evt)
      {              
        evt = getEvent(evt);
        var asc = getKeyCode(evt);
        var chr = getCharacter(asc);
 
        for (var i in this)
        {
          if (asc == i)
          {
            this[i](evt);
            break;
          }
        }
      }
      //
 
      // xBrowser event utilities
      function cancelEvent(evt)
      {
        evt.cancelBubble = true;
        evt.returnValue = false;
        if (evt.preventDefault) evt.preventDefault();
        if (evt.stopPropagation) evt.stopPropagation();
        return false;
      }
      function getEvent(evt)
      {
        if( !evt ) evt = window.event;
        return evt;
      }
      function getTarget(evt)
      {
        var target = evt.srcElement ? evt.srcElement : evt.target;
        return target;
      }
      function getKeyCode(evt)
      {
        var asc = !evt.keyCode ? (!evt.which ? evt.charCode : evt.which) : evt.keyCode;
        return asc;
      }
      function getCharacter(asc)
      {
        var chr = String.fromCharCode(asc).toLowerCase();
        return chr;
      }
      //
 
      function handleEnterKey(evt)
      {      
        var target = getTarget(evt);
        var targetTabIndex = target.tabIndex;
        var nextTabIndex = targetTabIndex+1;
 
        var nextElement = getElementByTabIndex(nextTabIndex);
        if( nextElement )
        {
          nextElement.focus();
          return cancelEvent(evt);
        }
 
        return true;
      }
 
      function getElementByTabIndex(tabIndex)
      {
        var form = document.forms[0];
        for( var i=0; i<form.elements.length; i++ )
        {
          var el = form.elements[i];
          if( el.tabIndex && el.tabIndex == tabIndex )
          {
            return el;
          }
        }
 
        return null;
      }
 
      // Setup our Key Commands
      var keyMap    = new Array();
      var ENTER     = 13 // ASCII code
      keyMap[ENTER] = handleEnterKey;
 
      // Add the keypress listner to the document object for global capture
      bind(document, 'keypress', keyMap, handleKeystroke);
    </script>
  </head>
  <body onload="document.forms[0].elements[0].focus();">
    <form id="form1" name="form1">
      Textbox One: <input type="text" id="txtOne" name="txtOne" tabindex="1" /><br />
      Textbox Two: <input type="text" id="txtTwo" name="txtTwo" tabindex="2" /><br />
      <input type="submit" value="Submit" />
    </form>
  </body>
</html>

http://blogs.meetandplay.com/WPierce/archive/2006/10/09/Tab_with_Enter_Key.aspx

R.K
0
 
ThinkPaperIT ConsultantCommented:
take a look at this.. somewhat interesting.. instead of event 13 (enter) they use onunfocus on the last textbox:
http://www.htmlgoodies.com/beyond/javascript/article.php/3472341

or you could do a variation of this:

<textarea onkeypress="if (event.keyCode == 13) {this.form.submit();}">

for your code it would be: if (event.keyCode == 13)

for tabs, just set the tab order for each texbox by using tabindex

<input type="text" tabindex=1 name="Name">
<input type="text" tabindex=2 name="Address">
<input type="text" tabindex=3 name="City">


0
 
ftaco96Commented:
     First: <input type="text" id="txt1" name="txt1" onkeydown="return checkName(this);"><br>
      Second: <input type="text" id="txt2" name="txt2" onkeydown="return checkName(this);"><br>

and in your function...

function checkname(oTextbox)
{
      oTextbox.focus;
      var val = window.event.keyCode;
      alert(val);
      if (val == 8 || val == 46){
            //Do nothing if backspace or delete is pressed
      }
      else
      {
            var temparray
            this.textbox = oTextbox
            var temptext = oTextbox.value.length
            if (val == 9 || val == 13) {
                  var textval = check_name(oTextbox.value)
                  temparray =  check_fields(oTextbox.value).split("/")
                  document.getElementById('txtfirstname').value = temparray[0]
                  document.getElementById('txtm').value = temparray[1]
                  document.getElementById('txtareacode').value = temparray[2]
                  document.getElementById('txtprefix').value = temparray[3]
                  document.getElementById('txtsuffix').value = temparray[4]
                  oTextbox.value += textval
                  var oRange = oTextbox.createTextRange();
                  oRange.moveStart("character", temptext);
                  oRange.moveEnd("character",  oTextbox.value.length - textval.length);
                  oRange.select();
                  oTextbox.focus();

                  // stops the keystroke from "bubbling up" to the form level
                  if (document.all) { window.event.cancelBubble=true; }  
                  // returns false to onkeydown event to prevent the tab action
                  return false;  
            }                  
      }
      // returns true to onkeydown event to continue
      return true;
}

You must use the onkeydown event, because the tab focus changes right after that.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now