简体   繁体   中英

How to redirect to another page after click on submit button in form with required inputs

I need to redirect to index.html after clicking on button in a form. I tried this:

$("#btn").on("click", function() { 
  window.location.replace("index.html");
  localeStorage.clear();
})

However in the form I have required inputs, so when I had some empty required input, it redirected, but at the same time it said that I must write something to input.

I need to redirect to index.html after successful form submission. Like on a eshop after submitting an order

what you could do is to verify that the inputs are present before the redirect:

$("#btn").on("click", function() { 
   // do some checks

   //if checks ok call redirect, if ko returns
   window.location.replace("index.html");
   localeStorage.clear();
})

Firstly, if you want the form to be validated first before the redirection you need to place the event on the submit of the form, not the click of the button.

Secondly, performing a redirect in JS when the form is submit is redundant; just set the action of the form to where you want the user to be sent.

With the above in mind, try this:

<form id="yourForm" action="index.html">
  <input type="text" name="foo" required />
  <!-- Some more 'required' form controls... -->

  <button type="submit">Submit</button>
</form>
$("#yourForm").on("submit", function() { 
  localeStorage.clear();
});

You can verify the values, use fetch to send the form and then redirect.

( You can add some gestion of server response before redirect. Like "Login already in database ... )

$("#btn").on("click", function() { 
  const verif = *verifAndFormat(...)* // function that return json like {valid:true , data:... }
  if( verif.valid ){
    fetch( URL , {method:'POST', body: verif.data} )
    .then( resp =>{
      /*some operations*/
      localeStorage.clear();
      window.location.replace("index.html");
    })
    .catch( err => /*error gestion*/
  }else{
    /*Invalid value gestion*/
  }
})
 $(function(){  
    $('#btn').On('click', function() {
window.location.href="../index.html";
}
}

And also you can call it form html coding on click event to call function submit and redirect from that.. html coding

<input type="button" id="btn" onclick="submit()"/>

Javascript coding

function submit(){
window.location.replace("http://webpagename.index.html");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM