Home > Net >  Change display value of a div based on input value
Change display value of a div based on input value

Time:01-18

I want a button to appear when someone enters the correct value (a number) into a input type="number". I tried var check=document.getElementById("buttonID").value == "1" and then an if statement, but I must have done something very wrong.

This is how I want it to work.

  1. input: 1 (press enter)

  2. button appears

I currently have a button set to display:none and an input but that's it.

    #my input
    <div >
        <input id="val" type="number">
    </div>
   #the button i want to appear when the input value is 1
   <div >
        <a href="link" target="_blank"><button id="button2">
            <img  src="image.png">
        </button></a>
    </div>

my code is messy but I hope you get what I'm trying to do

CodePudding user response:

You need to check the value whenever the input changes. That can be achieved by using onkeyup on the input element.

Working example:

function checkInputValue(event){

  // Check if ENTER has been pressed
  if(event.key==="Enter"){
  
    // Check the value of the input
    if(document.getElementById("myInput").value==="1")
    {
      // Show button
      document.getElementById("hideButton").style.display="block";
    }
    else
    {
      // Hide button
      document.getElementById("hideButton").style.display="none";
    }
  }
}
<input id="myInput" onkeyup="checkInputValue(event)">
<button id="hideButton" style="display:none;">BUTTON</button>

  • Related