Search code examples
javascriptformshttp-redirectsubmission

How to redirect if form submission is successful and remains on the page its false using js


Here is my code. I want to redirect the page after successful form submission and it remains on that page and the user needs to fix the error

<form id="form_1" name="form" action="#" method="POST">
  <div class="btn-group" data-toggle="buttons">
    <input class="radio_btn" type="radio" name="group1" value="true">Yes
    <input class="radio_btn" type="radio" name="group1" value="false">No
  </div>
  <div class="btn-group" data-toggle="buttons">
    <input class="radio_btn" type="radio" name="group2" value="true">Yes
    <input class="radio_btn" type="radio" name="group2" value="false">No
  </div>
  <button type="submit">Submit</button>
</form>

<script>
  var form = document.querySelector('#form_1');
  var radioList = form.querySelectorAll('.radio_btn');
  form.addEventListener('submit', function() {
    for (var i = 0, length1 = radioList.length; i < length1; i++) {
      if (radioList[i].getAttribute('value') == 'false' && radioList[i].checked) {
        alert("error");
        return false;
      } else {
        return true;
        window.location.assign("http://worldlivecricket.com");
      }
    }
  });
</script>

Solution

  • you can do it like this using jquery

    $("#form_1").on("submit",function(e){
       if(your validation) {
          // redirect 
       } else {
          e.preventDefault();
       }
    });
    

    here e.preventDefault(); will stop the page from reloading