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

Time:10-30

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.

CodePudding user response:

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()"> 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

Add a eventListener:

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

CodePudding user response:

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" />
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related