JavaScript check checkbox checkbox is checked

Source: Internet
Author: User

Let's say there's a checkbox named CheckBox1 on the Web page with a form,form named Form1.

The code is as follows

var f = document.form1;
var sum=0;
if (f.checkbox1.length) {
for (var i=0;i <f.checkbox1.length;i++) {
if (f.checkbox1[i].checked==true)
sum=sum+1;
}
}else{
if (f.checkbox1.checked) {
Sum=1;
}
}
Console.log (sum);

Note that the outermost if judgment, f.checkbox1.length returns undefined when there is only one checkbox item.

Look at one more.

The code is as follows

<script>
function test ()
{
var x=document.getelementsbyname ("enjoy[]");
var Issel=false;
for (Var i=0;i<x.length;i++)
{
if (x[i].checked)
{
Issel=true;
return Issel;
}
}
return Issel;
}
</script>
<body>
<form id= "Form1" Name= "Form1" method= "Post" action= "" >

<input type= "checkbox" Name= "enjoy[]" id= "enjoy["/>
Eat
<input type= "checkbox" Name= "enjoy[]" id= "enjoy["/>
Drink

<input type= "Submit" name= "button" id= "button" onclick= "Alert (Test ());" value= "Submit"/>
</form>

Get to the selected checkbox there are several, the next operation will not be more introduced it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.