Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Conditional Confirmation

Need to use Javascript confirm function only if certain field has value


Robert Poole

1:07 pm on Aug 19, 2010 (gmt 0)

5+ Year Member

Hey everybody

I've just started using the javascript confirm feature when creating delete buttons or similar. However, I was recently asked to create a form which will send an email if the "Send Email" checkbox is checked. Not only that, if said checkbox is checked I need a confirmation when they submit the form. If the checkbox isn't checked then they can submit the form without confirmation.

Anyone got any ideas on how I would go about doing this?


1:30 pm on Aug 19, 2010 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

Assuming your markup is something along these lines:

<form id="theForm" ...>
<input type="checkbox" name="sendEmail">

You could attach an onsubmit listener to your form. Here is the quick n' dirty approach... place this script just before your closing </body> tag:

<script type="text/javascript">
(function () {
// Attach onsubmit listener to your form
var theForm = document.getElementById('theForm');
theForm.onsubmit = function () {
var result = true;
if (this.sendEmail.checked) {
result = confirm('Are you sure you want email?');
return result;

This is the quick n' dirty approach because it's assigning an event handler rather than an event listener. There can only be one event handler, though there can be any number of event listeners. However, there are cross browser incompatibilities with how to attach an event listener, so I will leave that as an exercise for you. Alternatively, you could use one of the popular frameworks like jQuery or YUI, which provide convenient methods for attaching listeners.

Robert Poole

1:34 pm on Aug 19, 2010 (gmt 0)

5+ Year Member

Thanks for your speedy response Fotiman. I'll try implementing this technique now and see how I get on...

Robert Poole

1:56 pm on Aug 19, 2010 (gmt 0)

5+ Year Member

Okay so I dumped that code in the bottom of my script and it seems to do the job perfectly - thanks very much indeed!

Featured Threads

Hot Threads This Week

Hot Threads This Month