情况:我想创建一个简单的代码,用户必须选择至少一个扩展才能继续。 用户应选择至少一个或多个扩展名,否则将显示警告消息。
问题:问题是,如果只有一个扩展可供选择,无论是否选中,都会出现警告消息,不允许注册完成。
//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; }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; }最满意答案
从浏览器的早期阶段开始,如果只有一个带有产品名称的表单控件,那么:
document.checkForm.elements["product"];将返回对该控件的引用,而不是您期望的集合。 默认情况下,此类控件没有length属性,因此:
arrCheckboxes.length返回undefined和
i < arrCheckboxes.length是假的,所以永远不会输入循环。
要解决此问题,请使用始终返回集合的querySelectorAll :
var arrCheckboxes = document.checkForm.querySelectorAll('[name=product]');在IE 8+和其他任何地方都受支持。 一个更简单的代码版本(假设它在函数体中):
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;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.lengthreturns undefined and
i < arrCheckboxes.lengthis 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;更多推荐
发布评论