Being fairly new to JavaScript, I am struggling with how to target and validate specific areas of a form.
I have created a simple web form, which consists of two text input fields for first name and last name. A checkbox with four options, and a submit button. With the form created, I wish to ensure the user:
I have attempted number 2 and have so far got the following:
function checkBox (){
var cbx = document.getElementById("myForm").cbx;
var chbx = false;
for (i=0; <cbx.length; i++) {
if(cbx[i].checked){
chbx = true;
// if not produce an alert
if (!chbx) {
alert("No checkboxes selected");
}
If the above is functionally correct, it only works when no checkboxes are selected, what if too many are selected? How do i go about these three problems?
First things first, you have some syntax errors. Please try the following code and see if it's working any better.
function checkBox (){
var cbx = document.getElementById("myForm").cbx;
var chbx = false;
for (i=0; <cbx.length; i++) {
if(cbx[i].checked){
chbx = true;
// if not produce an alert
}
if (!chbx) {
alert("No checkboxes selected");
}
}
}
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.