简体   繁体   中英

Select only one checkbox in each checkbox group in javascript

<script>
function tryThis(element){

    if(element.checked){
        element.classList.add("marked");
    }else{
        element.classList.remove("marked");
    }

    if(document.getElementsByClassName("marked").length>1){
      alert("Please select only one check box");
        element.checked=false;
        element.classList.remove("marked");
    }
    if(document.getElementsByClassName("marked").length==0){
         alert("Please select one check box");
    }
}
</script>
<div>
<input type="checkbox" name="gender" value="male" onclick="tryThis(this);"/>
<input type="checkbox" name="gender" value="female" onclick="tryThis(this);"/>
<input type="checkbox" name="gender" value="unknown" onclick="tryThis(this);"/>
</div>

<div>
<input type="checkbox" name="report" value="no" onclick="tryThis(this);"/>
<input type="checkbox" name="report" value="yes" onclick="tryThis(this);"/>
<input type="checkbox" name="report" value="other" onclick="tryThis(this);"/>
</div>

This is a small example of the code I've been trying out (I found this function from another thread). The problem I have here is that I want one checkbox from each checkboxgroup to be selected but it turns out that one checkbox is being selected for all groups ie when I select 'male' in 'gender' I should be able to select 'yes' in report but that's not happening. What am I missing here?

You can do so with radio buttons

<input type="radio" name="age" value="10">10-20
<input type="radio" name="age" value="20">20-30
<input type="radio" name="age" value="30">30+

<input type="radio" name="sex" value="female">Female
<input type="radio" name="sex" value="male">Male

The "name" attribute groups buttons

This may be a start in the right direction. Note I can mess up the state by refreshing the page.

function tryThis(element){
    if(element.checked){
        element.classList.add("marked_" + element.name);
    }else{
        element.classList.remove("marked_" + element.name);
    }

    if(document.getElementsByClassName("marked_" + element.name).length>1){
      alert("Please select only one " + element.name + " check box");
        element.checked=false;
        element.classList.remove("marked_" + element.name);
    }
    if(document.getElementsByClassName("marked_" + element.name).length==0){
         alert("Please select one " + element.name + " check box");
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM