Problems with outputting error after submit empty fields

Viewed 37

i have a problem with my script, the only problem is outputting error. the error just bricks after submit_button. so that means when the fields are empty it has to output error and it works but the problem the output just bricks

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form method="post">
  <input type="text" id="text_field1" />
  <input type="text" id="text_field2">
  <button type="submit" id="submit_button">Submit</button>
  <button type="submit">Submit</button>
  <p id="error_resp"></p>
</form>
<script>
  $("#submit_button").click(function() {
    if ($("#text_field1").val() == "")
      $('#error_resp').text('please fill the required field');
    else if ($("#text_field2").val() == "")
      $('#error_resp').text('please fill the required field');
    else
      return true;
  });
</script>

1 Answers

There are few issues in your form HTML.

  1. You are not using preventDefault() method which will prevent the default behavior of a form so the inout can be validated.
  2. Also, you do not need check empty input like == "" You can just ! to say if my input is empty then show error message
  3. You are displaying errors in error_resp ideally use .html to clear the previous message and replace with new message

You can read more about .html here

Run snippet to below to see it working.

$("#submit_button").click(function(e) {
  e.preventDefault();
  if (!$("#text_field1").val()) {
    $('#error_resp').html('please fill the first required field');
  } else if (!$("#text_field2").val()) {
    $('#error_resp').html('please fill the second required field');
  } else {
    $('#myForm').submit();
    console.log('All looking good. Form will submit now')
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="myForm" action="filename.php">
  <input type="text" id="text_field1" />
  <input type="text" id="text_field2">
  <button type="submit" id="submit_button">Submit</button>
  <p id="error_resp"></p>
</form>

Related