Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

checkbox - javascript to create multiple checkboxes in for statement

Hi I am trying to create a bunch of checkboxes without having to make each one currently I have:

function test(obj) {
    if (document.getElementByID("info").checked == true) { 
        document.getElementById("gender")[0].disabled = true;
    }
}

and it works for one checkbox but I have been trying to use the code below:

function test(obj) {
    var x = obj.name;
    var rowCount = $('#List tr').length;
    for (var i = 0; i rowCount-1; i++) { 
        if (x == document.getElementByID("info"["+i+"]).checked == true) {
            document.getElementById("gender"["+i+"]).disabled = true;
        }
    }
}

to create as many checkboxes as I want without me having to make each one but it doesn't seem to be working.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ok, lets start from the beginning:

To create a check-box in javascript you must do something like this:

var checkbox = document.createElement("input");
checkbox.type = "checkbox";

Then to add your checkbox into a div on your webpage you would do something like:

document.getElementById("your_div_id").appendChild(checkbox);

Then to see if the checkbox is checked you look at the "checked" property like so:

var isChecked = !!document.getElementById("your_checkbox").checked;
if(isChecked == true){
    // Do whatever you want
}

Here's a function that would loop through a bunch of checkboxes

function testCheckBoxes(container_id){
    var checkboxes = document.querySelector("#" + container_id + " > input[type='checkbox']");
    for(var i = 0; i < checkboxes.length; i++){
        if(!!checkboxes[i].checked == true){
            // Your code
        }
}

[Side Note: I'm using document.querySelector for consistency but since I think you're using jquery then use $ instead] If you want to do something when someone clicks on your checkbox the use an event listener:

var list = document.getElementsByClassName("checkbox");
for(var i = 0; i < list.length; i++){
    list[i].addEventListener('click', function(event){
        if(!!event.target.checked == true){
            // Do something
        }
    }, true);
}

Hopefully this is enough to get you started. Good Luck =)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...