Validating a multiple-checkbox (checkbox) value in a form (form) with Javascript effects

Source: Internet
Author: User
This paper introduces a more general method to get the checkbox value, which is helpful to the novice.
Copy Code code as follows:

<script type= "Text/javascript" >
Note: Use Javascript to validate the values of multiple-selection boxes (checkboxes) in forms (form)
Author: codebit
function Getcheckboxvalue (checkbox)
{
if (!checkbox.length && checkbox.type.toLowerCase () = = ' checkbox ')
{return (checkbox.checked)? Checkbox.value: ';}
if (checkbox[0].tagname.tolowercase ()!= ' Input ' | |
Checkbox[0].type.tolowercase ()!= ' checkbox ')
{return ';}
var val = [];
var len = checkbox.length;
for (i=0; i<len; i++)
{
if (checkbox[i].checked)
{
Val[val.length] = Checkbox[i].value;
}
}
Return (Val.length) Val: ';
}
</script>

Like radio, it is the same name, there are multiple values, we can't follow the normal text box when we get the checkbox value. value, but to determine which is selected.

When a set of checkbox has more than one option, we can determine whether an option is selected to return a value by looping, Checkbox[i], but when a set of CheckBox has only one option, the way to get the value changes, in the code ( checkbox.checked)? Checkbox.value: '; Directly to determine if it is selected, and then return the corresponding value.

The code passed in above is a CheckBox object, such as:
Copy Code code as follows:

var checkboxtest = document.forms[' testform '].elements[' checkboxtest '];
if (Getcheckboxvalue (checkboxtest) = = ")
{ ...... }

Perform the actions you want based on the results of your judgment.
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.