views:

299

answers:

1

Hi guys, this is my first post on stackoverflow, I hope you can help me out!

I need to have javascript/ajax validation for a checkbox on a form I am making, the checkbox is deselected by default but when it is ticked, a javascript box should pop up displaying this text, "You have selected the newsletter checkbox, are you sure you would like to receive our newsletter?" when they click the submit button.

If they click yes, the the form should submit the newsletter checkbox info, if not, the form should still submit, but without the newsletter checkbox info.

I would really appreciate the help, thank you.

+2  A: 

Welcome to SO!

You will need a Javascript function that runs when your form is submitted. From there, you will check if the box is checked, if so, use confirm() to show your message. If they select no, then you uncheck the box via Javascript and your form submits as usual.

Pseudo code:

<script language="javascript">
        function checkNewsLetter()
        {
            var chk = document.getElementById('chk1');
            if ((chk.checked) && (!confirm('Are you sure you wish to sign up?')))
                chk.checked = false;
        }
</script>

<form onsubmit="return checkNewsLetter();">
        <input type="checkbox" id="chk1" name="chk1" />
        <input type="submit" />
</form>

I would also recommend checking out jQuery for all your Javascript needs, it's very easy to use.

wsanville
That worked perfectly, thanx a million wsanville!I'll be implementing the code into the site soon, I'll post here again if I run into any problems. I'll definitely have a look at jQuery then.Thanx again!