-1

I have an in input required. As I am using input type="submit" it is working fine but I am using input type button. When I used input type button the input requirement doesn't work. Please help

When I used the code below with type submit the required is working

<script>
function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false;
  }
}
</script>

<form name="add_name" id="add_name">
  Name: <input type="text" name="fname" required>
  <input type="submit" value="Submit">
</form>

But my form is as below. I am using input type button and the requirement is not working. How to solve it please.

<form name="add_name" id="add_name">
Name: <input type="text" name="fname" required>
<input type="button" value="Submit">
</form>
  • _"When I used input type button the input requirement doesn't work"_ - So why don't you show us that code? When posting a question, you should show us the code that _doesn't_ work together with a proper explanation of "doesn't work" mean in this context and explain what debugging you've done. – M. Eriksson Nov 28 '20 at 09:46
  • @MagnusEriksson I've edited my question. Hope you understand clearly now – JohnRaaj Seager Nov 28 '20 at 10:12
  • Did you read the answers on the link I posted? And where are you actually calling the validateForm()-function? – M. Eriksson Nov 28 '20 at 10:15

1 Answers1

-2

what`s up?

You just need add even listener on your button (not form), because form tag react onSubmit, but doesn`t react onClick buttons inside (like yours).

There is your right code:

<form name="myForm" action="/action_page.php" method="post">
  Name: <input type="text" name="fname">
  <input type="submit" value="Submit" onclick="return validateForm()">
</form>