Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - How to dynamically create a checkbox in JavaScript

We are dynamically creating multiples checkbox in JavaScript. But, there is one problem. The checkbox has been created, but it's label is not visible. We confirmed that it was created properly by the developer tool. But I can't see the label on the web. How do we deal with this? I attach the photo. I also attach the code.

radio.setAttribute("type", "checkbox");
radio.setAttribute("id", "lo_radio");
radio.setAttribute("name", "choose");
radio2.setAttribute("type", "checkbox");
radio2.setAttribute("id", "lo_radio2");
radio2.setAttribute("name", "choose");
... 
 if(j==1){
        var color = document.getElementById("#color_li");
        //ul.insertBefore(radio, color);
        var label = document.createElement("label");
        ul.insertBefore(label, color);
        label.appendChild(radio);
        radio.innerHTML = radio.innerHTML + "10?";
        label.appendChild(radio);
    
//      ul.insertBefore(radio2, color);
        ul.insertBefore(label, color);
        label.appendChild(radio2);
        radio2.innerHTML = radio2.innerHTML + "30?";
        ul.insertBefore(lo_select, color);


        $("#lo_li").click(function() {  
            if($("#lo_select").is(":visible")){
                  $("#lo_select").slideUp();
            }
            else{   
                $("#lo_select").slideDown();
            }});

    }
...
//HTML
<section id = "section1_r" style = "background-color : #525252; font-family : a?????1, sans_serif">
<div id = "a2">
</div>

enter image description here

HTML in browser console:

enter image description here

** ?? = "location" (in Korean)


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

1 Reply

0 votes
by (71.8m points)

If you are trying to create a checkbox programmatically:

const label = document.createElement("label");
const checkbox = document.createElement("input");
checkbox.type="checkbox";
checkbox.id="some-id";
checkbox.name="some-name";
const textContent = document.createTextNode("Label text content");

label.appendChild(checkbox);
label.appendChild(textContent);

document.body.appendChild(label);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...