Javascript YES NO confirmation box

This is a useful script to confirm a users intention to do something, like submit a form, or visit a different page.

Try these examples:

Example 1:

Example 2: Go to a New Page >>

 

Example 1: Confirming a Submit Form

First we have to create the javascript function, this can be anywhere on your HTML course, but it usual in the between <head> </head> sections to keep your page itself clear of code

Javascript Human Person Language

<script type="text/javascript">

 

function submitForm() {

 

if (confirm("Submit this form?") == false)

{

return false;

}

 

 

}

 

</script>

Tell the browser that this part is javascript code

 

Start a function called 'submitForm'

 

The part 'Confirm("your words") ' opens up the dialog box

When you press 'OK' the cofirm window give the value 'true', if you click 'cancel' if gives back the value 'false'

 

The line 'return false' cancels the action of the form

 

End the function

 

End the javascript bit

This code then goes on the form itself

HTML Form Human Person Language

<a href="newpage.html" onclick="return confirmNewPage()">New Page</a>

A normal link, but when its clicked, it first runs the confirmNewPage function, which either permits, or cancels the link

 

Example 2: Openning page from a link

 

Javascript Human Person Language

<script type="text/javascript">


function confirmNewPage() {
if (confirm("Go to the new page?") == false ) { return false; }
}


</script>

 

 

 

Same code, if the cancel button is clicked, we pass the value 'false' back, and cancel the action, which was to go to another page

This code then goes on the form itself

HTML Form Human Person Language

<form method="post" action="newpage.html" onsubmit="return submitForm()">


<input type="text" name="textfield" id="textfield" />
<input type="submit" name="button" id="button" value="Submit" />

 

</form>

On submit, it runs the function submitForm, becuase of the word 'return' infront, it is waiting for a true or false value to be given back, telling whether it's ok to carry on and submit the form'