0

Please, I'm trying to create a simple form validator that can be submitted if the input value is 1-10, but the form I created doesn't submit, how can I fix that?


<p id="demo"></p>
<br>
<form action="welcome.php">

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>
</form>

<script>
function myFunction() {
  let x = document.getElementById("numb").value;
  let text;
  if (isNaN(x) || x < 1 || x > 10) {
    text = "Input not valid";
  } else {
    text = "Input OK";
  }
  document.getElementById("demo").innerHTML = text;
}
</script>
john
  • 7
  • 3
  • 1
    I assume you want to submit the form with JS, so `document.querySelector("form").submit()` would be a rough and ready way to do it. – ggorlen Sep 17 '22 at 02:39

1 Answers1

0

The reason is you have not invoke submit method in your code,to do this you can using an extra variable to store the input checking result

function myFunction() {
  let x = document.getElementById("numb").value;
  let text;
  let valid=false;
  if (isNaN(x) || x < 1 || x > 10) {
    text = "Input not valid";
  } else {
    text = "Input OK";
    valid=true;
  }
  document.getElementById("demo").innerHTML = text;
  if(valid){
   document.getElementById("test_form").submit(); 
  }
}
<p id="demo"></p>
<br>
<form action="welcome.php" id="test_form">

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>
</form>
flyingfox
  • 13,414
  • 3
  • 24
  • 39