bill maxfith bill maxfith - 3 months ago 9
HTML Question

How to submit for after all the fields are filled in JavaScript

Basically I have a HTML form that contains a textbox and a submit button, what I want is when I pressed submit button it should check for the textbox that it have no error then proceed with submission.

Here is my button code:

<form id="thisform">
<div id="Registeration" class="Registeration">
<input type="text" id="textbox" class="textbox"
placeholder="My textbox" name="fBox" maxlength="30"/>
</div>

<div class="Registration_Submit_Div">
<input type="submit" value="submitform" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn" onclick="submit()"/>
</div></form>

function(){
alert('hello');
return false;
}

Answer

Here's a plain JS example where the form is only submitted if the text is at least 5 characters long.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>

  <form method="POST" action="result.html" class="da-form">
    <input type="text" name="textbox" class="textbox">
    <input type="submit" class="submit">
  </form>

  <script>

    var formEl = document.querySelector('.da-form');
    var submitBtn = document.querySelector('.da-form .submit');
    var textEl = document.querySelector('.textbox');

    submitBtn.addEventListener('click', function(event) {
      event.preventDefault();
      if (textEl.value.length >= 5) {
        formEl.submit();
      } else {
        console.error('text should be at least 5 chars long');
      }
      console.log();
    });

  </script>

</body>
</html>