简体   繁体   中英

how to detect what the user have typed in input box in html & javascript

I want my input box to detect a text like this...

var input = document.getElemntById("inputbox");
function buttonclick() {
  if ((input = "h")) {
    input.innerHTML = "hello";
  }
}

This is by button click but i need to do this onkeyup() but I don't know how to.. if the user type h the input box suddenly make it hello how do I do this? Thanks in advance.

You really just need an onkeyup event on your html tag.

 var input = document.getElementById("inputbox"); function buttonclick() { if (input.value === "h") { input.value = "hello"; } }
 <input id="inputbox" onkeyup="buttonclick()">

When the key is lifted the function buttonclick() is called. You also need to grab the value of the input as the innerHTML does not refer to what is placed within the input box but rather the actual code that would be between lets say two <div> </div> tags.

Add a eventListener:

document.getElementById("inputbox").addEventListener("keyup", (e) => {
    if (e.target.value == "h") e.target.value = "hello"
}

You have to do following changes to work:

1) TYPO : You should use getElementById instead of getElemntById

var input = document.getElementById("inputbox");

2) You can use keyup event as

input.addEventListener( "keyup", changeInputValue )

3) When you are checking equality of two string, use === . = is for assignment.

input.value.trim() === "h"

4) You have to compare the value of the input with h .

input.value.trim() === "h"

NOTE: I've used trim method because if user added some space before h then it will still set hello . You can remove it if you don't want.

 var input = document.getElementById("inputbox"); function changeInputValue() { if (input.value.trim() === "h") { // input.value === "h" input.value = "hello"; } } input.addEventListener("keyup", changeInputValue)
 <input type="text" id="inputbox" />

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