简体   繁体   中英

AJAX/Javascript checkbox validation

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM