homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

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)

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)

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)

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)

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

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved