Lewis Pye February 2016

Javascript back button with confirm

Im trying to implement a back button onto a form I am designing which when pressed results in a confirmation popup allowing the user to select ok or cancel. The code I have for this button so far is as follows.

function goBack(){
    window.history.back();
    }
<button type="back" value="back" onclick="goBack()">Back</button>

The issue I am having is that most elements of the form are set as required, and therefore when the back button is clicked, the form asks for all fields to be completed first, please could someone show me how to get the button to go back without requesting the form to be completed first. Thanks

Answers


Julio M. February 2016

I only use the button for submitting a form, for this, input type button works properly.

<input type="button" onClick="javascript:history.back();" value="back" />


Vas Hanea February 2016

There is no type="back" for the buttons. Just use:

<button value="back" onclick="goBack()">Back</button>

or

<input type="button" onclick="goback()" value="Back"> 

or to be sure use a link:

<a href="javascript:history.go(-1);">Back</a>

Just don't use type="Submit" and make sure you don't have any functions that call form inputs validation when you leave that page!


Dustin Poissant February 2016

The problem is that back is not a valid type for a button. If you do not want the form to be submitted use the button type. This should solve your problem.

function goBack(){
  if(confirm("Are you sure?")){
    window.history.back();  
  }
}
<form>
  <!-- inputs here -->
  <input required />
  <button type='button' onclick='goBack()'>Back</button>
</form>

Post Status

Asked in February 2016
Viewed 1,321 times
Voted 9
Answered 3 times

Search




Leave an answer