Home > front end >  Input field not clearing
Input field not clearing

Time:10-31

I have an input field that asks the user for a number then generates a multiplication from 1 - 12 against the number.

<input type="text" id="integer" value="100" />

if the number entered in the input field is less than 1 and greater than 100, it will alert the user to enter a number between 1 and 100

if (integer < 1 || integer > 100) {
          alert(
            "Please enter a valid input \nEnter any number between 1 and 100"
          );}

After the alert, the input field should clear.

let integer = document.getElementById("integer").value

i have tried setting the input value to ""

if (integer < 1 || integer > 100) {
          alert(
            "Please enter a valid input \nEnter any number between 1 and 100"
          );
          integer = "";}

but the input isn't clearing.

CodePudding user response:

From my mind (without testing), while doing

let integer = document.getElementById("integer").value

You're not referencing the "value", but deep-copy the value, so either to clear input again do querySearch by calling:

document.getElementById("integer").value = ""

or make variable reference whole object like:

let integer = document.getElementById("integer")

and then use it like integer.value = "";

EDIT EXAMPLE:

let testInput = document.getElementById("testInput");
let testBtn = document.getElementById("testBtn");
let testOutput = document.getElementById("testOutput");
let testOutput2 = document.getElementById("testOutput2");

testBtn.addEventListener("click", () => {
  testOutput.innerHTML = testInput.value;
  
  if (testInput.value > 0 && testInput.value < 100)
    testOutput2.innerHTML = "good";
  else
    testOutput2.innerHTML = 'bad';
  
  testInput.value = "";
});
<div style="padding: 15px; border: 1px solid gray;">
  <input type="number" id="testInput" />
  <br />
  <button id="testBtn" type="button">Display and clear</button>
  <br /><br />
  <p>output value: <span id="testOutput"></span> | <span id="testOutput2"></span></p>
</div>

CodePudding user response:

<input type="text" id="integer" min="1" max= "100" value="100" />

  • Related