简体   繁体   English

使用JavaScript创建多个复选框

[英]Create multiple Checkboxes with JavaScript

I want to create multiple checkboxes with JavaScript. 我想使用JavaScript创建多个复选框。 I tried the following: 我尝试了以下方法:

var response= data;
        var container = document.createElement('div');
        var checkboxContainer = document.createElement('div');
        checkboxContainer.setAttribute('class', 'checkbox');
        var label;
        var checkBox;

        for(i=0;i<response.length;i++){
            label = document.createElement('label');
            checkBox = document.createElement('input');
            checkBox.type = "checkbox";
            checkBox.name = "selDates[]";
            checkBox.value = response[i]['date'];

            label.innerHTML = response[i]['date'] + " " + response[i]['typ'];
            label.appendChild(checkBox);

            checkboxContainer.appendChild(label);
            container.appendChild(checkboxContainer);
        }
        $("#downloadContent").prepend(container);

As I can see in the chrome developer tools it creates all my checkboxes, but only display one. 正如我在chrome开发人员工具中看到的那样,它创建了我的所有复选框,但只显示了一个。 All labels are displayed. 显示所有标签。

在此处输入图片说明

As you can see, one checkbox is displayed with all (3) labels. 如您所见,将显示一个带有所有(3)标签的复选框。

在此处输入图片说明

Here you can see a print screen of the code. 在这里,您可以看到代码的打印屏幕。

Why is there just one checkbox displayed? 为什么只显示一个复选框? For your information, I use Bootstrap 3 and jQuery. 供您参考,我使用Bootstrap 3和jQuery。

Thanks for your help! 谢谢你的帮助!

Yanick Yanick

The Javascript seems ok (except may be for adding checkboxContainer every time in the loop). Javascript似乎还可以(除了可能需要在循环中每次添加checkboxContainer之外)。

One possibility is that CSS makes the other checkboxes not visible. 一种可能是CSS使其他复选框不可见。

For example the style for those label s could be defined with position:absolute (thus all of them are visible, but one above the other), or display:none except for one... 例如,这些label s的样式可以使用position:absolute (因此它们都是可见的,但是一个在另一个之上)定义,或者display:none除了一个...

Hard to tell for sure without a minimal reproducible example. 没有最小的可复制示例,很难确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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