Checking to make sure at least one item has been selected in the checkbox list using javascript

I would like my code to check if one or more checkboxes have been selected in the checkbox list. If no checkboxes were selected, I would like window.alert to pop up saying "please select at least one interest." Currently, all it does is warn that nothing has been checked, even if you check the box.

My code looks like this:

<!DOCTYPE HTML>
<html>
<head>
<title>Web Site Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function confirmSubmit(){
    if(document.forms[0].interests.checked) {
         {window.alert("Thank you");}
    } else {
    {window.alert("Select at least one preference");
}
    return false;}
return true;
}

</script>
</head>
<body>
<h1>Web Site Registration Form</h1>
<h2>Personal Information</h2>
<form action="FormProcessor.html" method="get"
enctype="application/x-www-form-urlencoded" onsubmit="return confirmSubmit()">

   <p>Select areas of interest (select at least one)</p>
    <p><input type="checkbox" name="interests"
         value="entertainment">Entertainment<br />
    <input type="checkbox" name="interests"
         value="business">Business<br />
    <input type="checkbox" name="interests"
         value="music">Music<br />
    <input type="checkbox" name="interests"
         value="shopping">Shopping<br />
    <input type="checkbox" name="interests"
         value="travel">Travel</p>
    <p><input type="submit"></p>
    </form>
</body>
</html>

      

Note. The extra code in the header should contain all the data entered on the page that shows what was sent. This is my first post, so feel free to let me know if other information may help. Thank!

+3


source to share


2 answers


Add a script tag below the form you can use this

to pass the form to your callback. Use querySelector

for :checked

to search within a form for marked input.

<script type="text/javascript">
function confirmSubmit(form){
    if(form.querySelector(":checked")) {
        window.alert("Thank you");
        return true;
    } else {
        window.alert("Select at least one preference");
        return false;
    }
}

</script>

      

You can submit a form to your call by updating your listener onclick

;



<form action="FormProcessor.html" method="get"
enctype="application/x-www-form-urlencoded" 
onsubmit="return confirmSubmit(this)">

      

Here is a fiddle.

+1


source


With jQuery, you can do this:



function confirmSubmit(){
$('input').each(function(index, item) {
   if(item.checked){
     return true;
   }
});
}

      

0


source







All Articles