Solved

How to capture tab or enter key stroke?

Posted on 2006-11-13
3
17,593 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 125 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

Get HTML5 Certified

Want to be a web developer? You'll need to know HTML. Prepare for HTML5 certification by enrolling in July's Course of the Month! It's free for Premium Members, Team Accounts, and Qualified Experts.

Question has a verified solution.

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

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
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

626 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