Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

 $(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.

(在此.change()使用复选框状态更新文本框值。)

I use .click() to confirm the action on uncheck.

(我使用.click()来确认取消选中的操作。)

If the user selects cancel, the checkmark is restored but .change() fires before confirmation.

(如果用户选择“取消”,则复选标记会恢复,但是.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?

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

  ask by Professor Chaos translate from so

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

1 Answer

Tested in JSFiddle and 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'));        
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...