简体   繁体   中英

How do i get my keycode to focus the element?

If i leave it without a keycode it will work with every key but i'm trying to add the "/" key which is keycode "191" and now i can't get it to work. I've even tried using the preventDefault after it and still nothing. How do i properly write it to make it work? Yes i also have the keypress in my input line as well, it's not the problem.

 function setFocusToTextBox(field, event) {
if (event.keyCode === 191) {
    document.getElementById("order_number").focus();
    }
}

</script>
</head>

<body onLoad="document.chip_insert.chip_number.focus();">

<center>
<h1>Jeffers HomeAgain Microchip Entry</h1>


<form name="chip_insert"  id="chip_insert" action="<?php echo $PHP_SELF;?>" onsubmit="return validateForm()" method="post" onkeydown="setFocusToTextBox(field, event)">
Order Number: <input tabindex="1" maxlength="12" type="text" name="order_number"  id="order_number"  value="<?php echo $value; ?>"  required="required"onkeydown="return tabOnEnter(this,event)" onfocus="this.focus();this.select()" /><br /><br />
Tag Number: <input tabindex="2" maxlength="15" type="text" name="chip_number" id="chip_number" required="required" /><br /><br />
<input tabindex="7" type="submit" />
</center>
</form>

<br />

<!--End body content -->

</body>
</html>

The working of your snippet is also depends on the event you call from , try to call your function on keydown.

Below is your working code :

document.body.addEventListener("keydown",function(e) { 

if (e.keyCode === 191)

 alert('Correct');

else

 alert('wrong');

});

keyCode may vary for different key events.

Try this

 window.addEventListener('keydown', keydownCallback); function keydownCallback(event) { if (event.keyCode === 191) { setTimeout(setFocusToTextBox); // setTimeout prevents insertion of slash } } function setFocusToTextBox() { document.getElementById("order_number").focus(); } 
 <input id="order_number" placeholder="Press / and I will be focused" size="60"> 

  1. Press Run Code Snippet
  2. Click somewhere on the area around the input
  3. Press / and the input will be focused.

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