Javascript jQuery 复选框更改和单击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7031226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:19:58  来源:igfitidea点击:

jQuery checkbox change and click event

javascriptjqueryevent-handling

提问by Professor Chaos

$(document).ready(function() {
  //set initial state.
  $('#textbox1').val($(this).is(':checked'));

  $('#checkbox1').change(function() {
    $('#textbox1').val($(this).is(':checked'));
  });

  $('#checkbox1').click(function() {
    if (!$(this).is(':checked')) {
      return confirm("Are you sure?");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox1"/><br />
<input type="text" id="textbox1"/>

Here .change()updates the textbox value with the checkbox status. I use .click()to confirm the action on uncheck. If the user selects cancel, the checkmark is restored but .change()fires before confirmation.

这里.change()用复选框状态更新文本框值。我.click()用来确认取消选中的操作。如果用户选择取消,复选标记将恢复但.change()在确认之前触发。

This leaves things in an inconsistent state and the textbox says false when the checkbox is checked.

这会使事情处于不一致的状态,并且在选中复选框时文本框会显示 false。

How can I deal with the cancellation and keep textbox value consistent with the check state?

如何处理取消并保持文本框值与检查状态一致?

回答by kasdega

Tested in JSFiddleand does what you're asking for.This approach has the added benefit of firing when a label associated with a checkbox is clicked.

JSFiddle 中测试并执行您所要求的操作。当单击与复选框关联的标签时,此方法具有触发的额外好处。

Updated Answer:

更新答案:

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val(this.checked);

    $('#checkbox1').change(function() {
        if(this.checked) {
            var returnVal = confirm("Are you sure?");
            $(this).prop("checked", returnVal);
        }
        $('#textbox1').val(this.checked);        
    });
});

Original Answer:

原答案:

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val($(this).is(':checked'));

    $('#checkbox1').change(function() {
        if($(this).is(":checked")) {
            var returnVal = confirm("Are you sure?");
            $(this).attr("checked", returnVal);
        }
        $('#textbox1').val($(this).is(':checked'));        
    });
});

回答by Joseph Marikle

Demo

演示

Use mousedown

mousedown

$('#checkbox1').mousedown(function() {
    if (!$(this).is(':checked')) {
        this.checked = confirm("Are you sure?");
        $(this).trigger("change");
    }
});

回答by lko

Most of the answers won't catch it (presumably) if you use <label for="cbId">cb name</label>. This means when you click the label it will check the box instead of directly clicking on the checkbox. (Not exactly the question, but various search results tend to come here)

如果您使用<label for="cbId">cb name</label>. 这意味着当您单击标签时,它将选中该框,而不是直接单击该复选框。(不完全是问题,但各种搜索结果往往会出现在这里)

<div id="OuterDivOrBody">
    <input type="checkbox" id="checkbox1" />
    <label for="checkbox1">Checkbox label</label>
    <br />
    <br />
    The confirm result:
    <input type="text" id="textbox1" />
</div>

In which case you could use:

在这种情况下,您可以使用:

Earlier versions of jQuery:

Earlier versions of jQuery:

$('#OuterDivOrBody').delegate('#checkbox1', 'change', function () {
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

JSFiddle example with jQuery 1.6.4

使用 jQuery 1.6.4 的 JSFiddle 示例

jQuery 1.7+

jQuery 1.7+

$('#checkbox1').on('change', function() { 
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

JSFiddle example with the latest jQuery 2.x

带有最新 jQuery 2.x 的 JSFiddle 示例

  • Added jsfiddle examples and the html with the clickable checkbox label
  • 添加了 jsfiddle 示例和带有可点击复选框标签的 html

回答by zarun

Well .. just for the sake of saving a headache (its past midnight here), I could come up with:

好吧..只是为了避免头痛(这里已经过了午夜),我可以想出:

$('#checkbox1').click(function() {
  if (!$(this).is(':checked')) {
    var ans = confirm("Are you sure?");
     $('#textbox1').val(ans);
  }
});

Hope it helps

希望能帮助到你

回答by chris

For me this works great:

对我来说,这很好用:

$('#checkboxID').click(function () {
    if ($(this).attr('checked')) {
        alert('is checked');
    } else {
        alert('is not checked');
    }
})

回答by Developer

Here you are

这个给你

Html

html

<input id="ProductId_a183060c-1030-4037-ae57-0015be92da0e" type="checkbox" value="true">

JavaScript

JavaScript

<script>
    $(document).ready(function () {

      $('input[id^="ProductId_"]').click(function () {

        if ($(this).prop('checked')) {
           // do what you need here     
           alert("Checked");
        }
        else {
           // do what you need here         
           alert("Unchecked");
        }
      });

  });
</script>

回答by umer

if you are using the iCheck Jquery use the below code

如果您使用的是 iCheck Jquery,请使用以下代码

 $("#CheckBoxId").on('ifChanged', function () {
                alert($(this).val());
            });

回答by yoozer8

Get rid of the change event, and instead change the value of the textbox in the click event. Rather than returning the result of the confirm, catch it in a var. If its true, change the value. Then return the var.

去掉 change 事件,改为更改 click 事件中文本框的值。与其返回确认的结果,不如将其捕获在 var 中。如果为真,则更改该值。然后返回变量。

回答by Mrchief

Checkbox click and checking for the value in the same event loop is the problem.

单击复选框并检查同一事件循环中的值是问题所在。

Try this:

尝试这个:

$('#checkbox1').click(function() {
    var self = this;
    setTimeout(function() {

        if (!self.checked) {
            var ans = confirm("Are you sure?");
            self.checked = ans;
            $('#textbox1').val(ans.toString());
        }
    }, 0);
});

Demo: http://jsfiddle.net/mrchief/JsUWv/6/

演示:http: //jsfiddle.net/mrchief/JsUWv/6/

回答by Jason

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val($(this).is(':checked'));

    $('#checkbox1').change(function() {
        $('#textbox1').val($(this).is(':checked'));
    });

    $('#checkbox1').click(function() {
        if (!$(this).is(':checked')) {
            if(!confirm("Are you sure?"))
            {
                $("#checkbox1").prop("checked", true);
                $('#textbox1').val($(this).is(':checked'));
            }
        }
    });
});