单击按钮

时间:2016-07-17 11:08:51

标签: javascript jquery html

我在尝试通过单击按钮选择所有复选框时遇到了很多麻烦。

在创建消息传递系统时,我正在使用PHP while循环生成所有复选框,并且没有问题。

当我点击全部检查按钮时,它只会检查第一个复选框,由于某种原因,忽略下面的任何其他复选框。

我使用的代码如下:

<button type='button' name='btn-check' id='btn-check' class='btn btn-default btn-sm' onclick='check()'>Check All</button>

<input type='checkbox' name='cb_delete[]' id='cb_delete' value='$mID'>

<script type="text/javascript">
   function check() {
     document.getElementById("cb_delete").checked = true;
     $("#btn-check").attr('disabled','disabled');
     $("#btn-uncheck").removeAttr('disabled','disabled');
     $("#btn-delete").removeAttr('disabled','disabled');
   }
</script>

我已尝试将getElementById更改为getElementByTypeByName等,但仍然没有运气。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

原因是(很可能)您为每个checkbox使用相同的class属性。
The id attribute标识符,因此,整个文档中的必须是唯一的

尝试使用id代替<button type='button' name='btn-check' id='btn-check' class='btn btn-default btn-sm'>Check All</button> <input type='checkbox' name='cb_delete[]' class='cb_delete' value='$mID'>

$("#btn-check").click(function(){
    $(this).prop('disabled', true);
    $("#btn-uncheck").removeAttr('disabled');
    $('.cb_delete').prop('checked', true);
});

脚本:

public void actionPerformed(ActionEvent e) {
        if (!uiCreator.getTextArea().getText().equalsIgnoreCase("Beggining text")) {
            JOptionPane.showMessageDialog(null, "You must have main method first", "Error",
                    JOptionPane.ERROR_MESSAGE);
        } else {
            n = Integer.valueOf(JOptionPane.showInputDialog("..."));
            l = Integer.valueOf(JOptionPane.showInputDialog("..."));
            uiCreator.getTextArea()
                    .setText("Beggining text with few additions");

旁注 - It's not a good practice to use onClick attribute

答案 1 :(得分:1)

Working JSFiddle

由于您使用的是jQuery,因此可以通过替换

来解决此问题

document.getElementById("cb_delete").checked = true;

$(":checkbox").prop('checked', true);