每当选中或选中复选框时都会发出警报

时间:2014-06-05 06:34:55

标签: javascript jquery checkbox

我已尝试制作一个功能,只要检查表格中的复选框但是效果不佳,就会触发该功能。我试过在$(文件).ready中创建一个函数,但它也没有用。

这是我的HTML代码

<td id='row'><input type='checkbox' name='helloname' value="helloval" id='select'> hello </td>

这是我的功能

$(document.ready)(function () {
    $("#row input:checked'").each(function(){
        $('#select').click(function(){
           alert('clicked');
        });
    });

我的主要目标是计算所选的复选框,并且不允许用户检查超过3.但是现在我试图创建一个能够在选中复选框时识别的功能     });

5 个答案:

答案 0 :(得分:0)

要识别选中复选框,您可以使用:

$("#select").change(function() {
 if(this.checked) {
    alert('clicked');
}});

答案 1 :(得分:0)

请尝试以下操作:此处document.ready语法已更正并且jquery已修改,以使tdid='row'内的已选中复选框的总计数为 $(document).ready(function(){ $("#row input[type='checkbox']").click(function(){ var count = $("#row input[type='checkbox']:checked").length; alert("total checked checkbox is : "+count); }); });

{{1}}

答案 2 :(得分:0)

此代码可以使用

        $(document).ready(function() {    
            $("#select").change(function() {
             if(this.checked) {
                alert('checked');
             }}); 
         });

答案 3 :(得分:0)

  1. 您的DOM准备就绪应为$(document).ready(function(){...
  2. 您不应通过仅迭代已检查的复选框来将点击绑定到每个复选框
  3. 使用事件委派进行绑定,然后在单击时检查状态。
  4. 根据您的问题,您的问题是禁止用户检查三个以上的复选框。

    您可以通过执行所有已检查输入的length来执行此操作,然后在长度超过3时覆盖新检查:

    演示:http://jsfiddle.net/abhitalks/uERSd/1/

    // bind click to all input of type checkbox inside #row via delegation
    $("#row").on("click", "input[type='checkbox']", function() {
        // check the length i.e. total number of inputs which are currently checked
        var tot = $("#row input[type='checkbox']:checked").length;
        if (tot > 3) {
            // disallow new checks if three are already checked
            this.checked = false;
        }
    });
    

答案 4 :(得分:0)

您的HTML

<table class="tableTable">
<tr id="tableTr">
<td id='row'><input type='checkbox' name='helloname' value="helloval" id='select'> hello </td>
<td id='row1'><input type='checkbox' name='helloname' value="helloval" id='select1'> hello1 </td>
<td id='row2'><input type='checkbox' name='helloname' value="helloval" id='select2'> hello2 </td>
<td id='row3'><input type='checkbox' name='helloname' value="helloval" id='select3'> hello3</td>
 </tr>
    </table>

JQUERY

$(document).ready(function(){    
$("#tableTr").on("click", "input[type='checkbox']", function() {
var count = $("#tableTr input[type='checkbox']:checked").length;
if (count > 3) {
this.checked = false;
alert("only 3 items can be checked");
        }
    });
 });
相关问题