最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

html - Validating checkbox with javascript - Stack Overflow

matteradmin5PV0评论

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
Post a comment

comment list (0)

  1. No comments so far