Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How to capture tab or enter key stroke?

Posted on 2006-11-13
3
Medium Priority
?
17,611 Views
Last Modified: 2011-08-18
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
Comment
Question by:tentavarious
3 Comments
 
LVL 23

Expert Comment

by:rama_krishna580
ID: 17933345
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
 
LVL 16

Expert Comment

by:ThinkPaper
ID: 17933350
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
 
LVL 9

Accepted Solution

by:
ftaco96 earned 500 total points
ID: 17933645
     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

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

926 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question