Cloudburst
Cloudburst

Reputation: 51

Select at least one option in HTML

Situation: I want to create a simple code whereby users must select at least one extension to proceed. Users should select at least 1 or more extension, else an alert message will appear.

Problem: The problem is, if there shall be only 1 extension available for selection, whether it is selected or not, the alert message will appear disallowing the registration to complete.

//Select atleast one extension 
 var arrCheckboxes = document.checkForm.elements["product"];
    var checkCount = 0;
    for (var i = 0; i < arrCheckboxes.length; i++) {
        checkCount += (arrCheckboxes[i].checked) ? 1 : 0;
    }
    if (checkCount > 0){
        return true;
    } else {
        alert("Select at least one Extension.");
        return false;
    }

Upvotes: 1

Views: 1812

Answers (1)

RobG
RobG

Reputation: 147403

It is a legacy from the very early days of browsers that if there is only one form control with a name of product, then:

document.checkForm.elements["product"]; 

will return a reference to that control, not a collection which you seem to expect. Such controls do not have a length property by default so:

arrCheckboxes.length

returns undefined and

i < arrCheckboxes.length

is false so the loop is never entered.

To fix that, use querySelectorAll which always returns a collection:

var arrCheckboxes = document.checkForm.querySelectorAll('[name=product]');

Supported in IE 8+ and everywhere else. A simpler version of your code (assuming it's in the body of a function):

var arrCheckboxes = document.checkForm.querySelectorAll('[name=product]');

for (var i = 0; i < arrCheckboxes.length; i++) {
    if (arrCheckboxes[i].checked) return true;
}
alert("Select at least one Extension.");
return false;

Upvotes: 1

Related Questions