最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Validating checkbox with javascript - Stack Overflow

programmeradmin1浏览0评论

I have problem to validate multi checkbox , I want to check if the user has selected at least one checkbox. Im try with document.getElementByClassName but does not work

HTML:

<form id="formupload" method="post" enctype="multipart/form-data" action="upload.php" name="formupload">
    <input onKeydown="javascript:validateForm();" id="txtFileName" name="txtFileName" />
    <input onKeydown="javascript:validateForm();" id="title" name="title" />
    <input onKeydown="javascript:validateForm();" id="keywords" name="keywords" />
    <input onKeydown="javascript:validateForm();" id="description" name="description" />


        <span class="niche">
        <input type="checkbox" value="1" name="channel[]" class="css-checkbox" id="box_1">
        <label class="css-label" name="lbl_1" for="box_1">Amateur</label>
        </span>

        <span class="niche">
        <input type="checkbox" value="2" name="channel[]" class="css-checkbox" id="box_2">
        <label class="css-label" name="lbl_2" for="box_2">Amateur</label>
        </span>

        <span class="niche">
        <input type="checkbox" value="3" name="channel[]" class="css-checkbox" id="box_3">
        <label class="css-label" name="lbl_3" for="box_3">Amateur</label>
        </span>

<button id="btnSubmit" class="btn lbtn upBtn" type="submit">Upload</button>
</form>

And Here is javascript:

function validateForm() {
    var txtFileName = document.getElementById("txtFileName");
    var titleTxt = document.getElementById("title");
    var tagsTxt = document.getElementById("keywords");
    var descTxt = document.getElementById("description");

    var isValid = true;
    if (txtFileName.value === "" || titleTxt.value === "" || tagsTxt.value === "" || descTxt.value === "" ) {
        isValid = false;
    }

    document.getElementById("btnSubmit").disabled = !isValid;

}

I have problem to validate multi checkbox , I want to check if the user has selected at least one checkbox. Im try with document.getElementByClassName but does not work

HTML:

<form id="formupload" method="post" enctype="multipart/form-data" action="upload.php" name="formupload">
    <input onKeydown="javascript:validateForm();" id="txtFileName" name="txtFileName" />
    <input onKeydown="javascript:validateForm();" id="title" name="title" />
    <input onKeydown="javascript:validateForm();" id="keywords" name="keywords" />
    <input onKeydown="javascript:validateForm();" id="description" name="description" />


        <span class="niche">
        <input type="checkbox" value="1" name="channel[]" class="css-checkbox" id="box_1">
        <label class="css-label" name="lbl_1" for="box_1">Amateur</label>
        </span>

        <span class="niche">
        <input type="checkbox" value="2" name="channel[]" class="css-checkbox" id="box_2">
        <label class="css-label" name="lbl_2" for="box_2">Amateur</label>
        </span>

        <span class="niche">
        <input type="checkbox" value="3" name="channel[]" class="css-checkbox" id="box_3">
        <label class="css-label" name="lbl_3" for="box_3">Amateur</label>
        </span>

<button id="btnSubmit" class="btn lbtn upBtn" type="submit">Upload</button>
</form>

And Here is javascript:

function validateForm() {
    var txtFileName = document.getElementById("txtFileName");
    var titleTxt = document.getElementById("title");
    var tagsTxt = document.getElementById("keywords");
    var descTxt = document.getElementById("description");

    var isValid = true;
    if (txtFileName.value === "" || titleTxt.value === "" || tagsTxt.value === "" || descTxt.value === "" ) {
        isValid = false;
    }

    document.getElementById("btnSubmit").disabled = !isValid;

}
Share Improve this question asked May 20, 2013 at 16:23 Milan MilosevicMilan Milosevic 4332 gold badges8 silver badges19 bronze badges 5
  • Where are you even attempting to determine the state of the check boxes? The JavaScript code posted only looks at some "untyped" input elements (which I guess default to text boxes?) but doesn't look at the check boxes at all. (Which are invalid, by the way. The input tags for the check boxes need to be closed.) – David Commented May 20, 2013 at 16:29
  • 1 You could try if (document.getElementById("formupload").querySelectorAll('input[name="channel[]"]:checked').length > 0) { } – Ian Commented May 20, 2013 at 16:29
  • 2 @David input elements do not need to be closed, as they may not contain any content. In fact, the spec forbids a closing tag. – Ray Nicholus Commented May 20, 2013 at 16:32
  • 1 @RayNicholus: Interesting. I didn't know that, but W3C just confirmed it. Too bad it's past the edit window for my ment. Either way, thanks for teaching me something new! – David Commented May 20, 2013 at 16:36
  • @David You are quite wele. After looking at the spec again, I learned that the closing tag was actually forbidden. I didn't recall that tidbit myself. Just knew that it was not required. I'm not sure if this detail is enforced in all browsers though. – Ray Nicholus Commented May 20, 2013 at 16:41
Add a ment  | 

2 Answers 2

Reset to default 1
var checkBoxes=document.getElementsByClassName("css-checkbox");

var booleanResult=false;
for(var i=0;i<checkBoxes.length;i++){
 if(checkBoxes[i].checked){
    booleanResult=true;
    break;
 }
}
if(booleanResult==false){
alert("invalid")
}

DEMO

Depending on whether you want to target the class or the name, you could try querySelectorAll:

var form = document.getElementById("formupload");
if (form.querySelectorAll('input[name="channel[]"]‌​:checked').length > 0) {

}
// or
if (form.querySelectorAll('input.css-checkbox​:checked').length > 0) {

}

Of course, you could add [type="checkbox"] to either of those, but it seems kind of unnecessary.

document.querySelectorAll has better support in older browsers and is more versatile.

Of course, if you want better support than that, you could get all checkboxes, loop through them and check if they have the class, then see if there's more than one checked. For example:

var form = document.getElementById("formupload"),
    inputs = form.getElementsByTagName("input"),
    i, cur, enoughChecked = false;
for (i = 0; i < inputs.length; i++) {
    cur = inputs[i];
    if (cur.type === "checkbox" && hasClass(cur, "css-class") && cur.checked) {
        enoughChecked = true;
        break;
    }
}
if (enoughChecked) {
    // At least 1 checkbox is checked
}

function hasClass(element, className) {
    return !!~(" " + element.className + " ").indexOf(" " + className + " "));
}

Reference:

  • https://developer.mozilla/en-US/docs/Web/API/Element.querySelectorAll
发布评论

评论列表(0)

  1. 暂无评论