jQuery 复选框更改和单击事件

发布于 2024-11-28 22:17:50 字数 909 浏览 0 评论 0原文

$(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"/>

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

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

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

一场春暖 2024-12-05 22:17:51

尝试

checkbox1.onclick= e => {
  if(!checkbox1.checked) checkbox1.checked = !confirm("Are you sure?");
  textbox1.value = checkbox1.checked;
}
<input type="checkbox" id="checkbox1" /><br />
<input type="text" id="textbox1" value='false'/>

Try

checkbox1.onclick= e => {
  if(!checkbox1.checked) checkbox1.checked = !confirm("Are you sure?");
  textbox1.value = checkbox1.checked;
}
<input type="checkbox" id="checkbox1" /><br />
<input type="text" id="textbox1" value='false'/>

愁以何悠 2024-12-05 22:17:51

试试这个:

    let checkbox = document.getElementById('checkboxId');
    if (checkbox.checked != true)
    {
        alert("select checkbox");
    }

Try this:

    let checkbox = document.getElementById('checkboxId');
    if (checkbox.checked != true)
    {
        alert("select checkbox");
    }
末蓝 2024-12-05 22:17:51
 $("#person_IsCurrentAddressSame").change(function ()
    {
        debugger
        if ($("#person_IsCurrentAddressSame").checked) {
            debugger

        }
        else {

        }

    })
 $("#person_IsCurrentAddressSame").change(function ()
    {
        debugger
        if ($("#person_IsCurrentAddressSame").checked) {
            debugger

        }
        else {

        }

    })
嗳卜坏 2024-12-05 22:17:50

JSFiddle 中测试并执行您所要求的操作。此方法的另一个好处是在单击与复选框关联的标签。

更新答案:

$(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);        
    });
});

原始答案:

$(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'));        
    });
});

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.

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'));        
    });
});
万劫不复 2024-12-05 22:17:50

演示

使用 mousedown

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

Demo

Use mousedown

$('#checkbox1').mousedown(function() {
    if (!$(this).is(':checked')) {
        this.checked = confirm("Are you sure?");
        $(this).trigger("change");
    }
});
内心荒芜 2024-12-05 22:17:50

如果您使用 ,大多数答案都不会捕获它(大概)。这意味着当您单击标签时,它将选中该框,而不是直接单击该复选框。 (不完全是问题,但这里往往会出现各种搜索结果)

<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>

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

早期版本的 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());
    }
});

使用 jQuery 1.6.4 的 JSFiddle 示例

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());
    }
});

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

  • 添加了 jsfiddle 示例和带有可单击复选框标签的 html

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)

<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:

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

  • Added jsfiddle examples and the html with the clickable checkbox label
埋情葬爱 2024-12-05 22:17:50

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

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

希望它有帮助

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

终陌 2024-12-05 22:17:50

迟到的答案,但您也可以使用 on("change"),即:

$('#check').on('change', function() {
     var checked = this.checked
    $('span').html(checked.toString())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="check"> <span>Check me!</span>

Late answer, but you can also use on("change"), i.e.:

$('#check').on('change', function() {
     var checked = this.checked
    $('span').html(checked.toString())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="check"> <span>Check me!</span>

所谓喜欢 2024-12-05 22:17:50

这里是

Html

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

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>

Here you are

Html

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

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>
枕梦 2024-12-05 22:17:50

对我来说这很有效:

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

For me this works great:

$('#checkboxID').click(function () {
    if ($(this).attr('checked')) {
        alert('is checked');
    } else {
        alert('is not checked');
    }
})
不羁少年 2024-12-05 22:17:50

只需使用点击事件
我的复选框 ID 是 CheckAll

     $('#CheckAll').click(function () {

        if ($('#CheckAll').is(':checked') == true) {

             alert(";)");
      }
    });

simply just use the click event
my check box id is CheckAll

     $('#CheckAll').click(function () {

        if ($('#CheckAll').is(':checked') == true) {

             alert(";)");
      }
    });
我们的影子 2024-12-05 22:17:50

摆脱更改事件,而是更改单击事件中文本框的值。与其返回确认的结果,不如将其捕获在 var 中。如果为真,则更改该值。然后返回变量。

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.

躲猫猫 2024-12-05 22:17:50

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

试试这个:

$('#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);
});

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

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/

我的奇迹 2024-12-05 22:17:50

如果您使用 iCheck Jquery 使用以下代码

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

if you are using the iCheck Jquery use the below code

 $("#CheckBoxId").on('ifChanged', function () {
                alert($(this).val());
            });
海拔太高太耀眼 2024-12-05 22:17:50

试试这个

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

Try this

$('#checkbox1').click(function() {
        if (!this.checked) {
            var sure = confirm("Are you sure?");
            this.checked = sure;
            $('#textbox1').val(sure.toString());
        }
    });
黒涩兲箜 2024-12-05 22:17:50
$(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'));
            }
        }
    });
});
$(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'));
            }
        }
    });
});
ㄖ落Θ余辉 2024-12-05 22:17:50
// this works on all browsers.

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

    $('#checkbox1').change(function(e) {
        this.checked =  $(this).is(":checked") && !!confirm("Are you sure?");
        $('#textbox1').val(this.checked);
        return true;
    });
});
// this works on all browsers.

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

    $('#checkbox1').change(function(e) {
        this.checked =  $(this).is(":checked") && !!confirm("Are you sure?");
        $('#textbox1').val(this.checked);
        return true;
    });
});
稀香 2024-12-05 22:17:50
$('#checkbox1').click(function() {
    if($(this).is(":checked")) {
        var returnVal = confirm("Are you sure?");
        $(this).attr("checked", returnVal);
    }
    $('#textbox1').val($(this).is(':checked')); 
});


<div id="check">
    <input type="checkbox" id="checkbox1" />
    <input type="text" id="textbox1" />
</div>
$('#checkbox1').click(function() {
    if($(this).is(":checked")) {
        var returnVal = confirm("Are you sure?");
        $(this).attr("checked", returnVal);
    }
    $('#textbox1').val($(this).is(':checked')); 
});


<div id="check">
    <input type="checkbox" id="checkbox1" />
    <input type="text" id="textbox1" />
</div>
蓝色星空 2024-12-05 22:17:50

我不知道为什么每个人都把事情搞得这么复杂。
这就是我所做的一切。

if(!$(this).is(":checked")){ console.log("on"); }

I am not sure why everyone is making this so complicated.
This is all I did.

if(!$(this).is(":checked")){ console.log("on"); }
深居我梦 2024-12-05 22:17:50
$('#checkboxId').change(() => {
    if($('#checkboxId').is(':checked')) {
        $('#checkboxStatus').text('Active')
    } else {
        $('#checkboxStatus').text('Inactive')
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<label><input type="checkbox" id="checkboxId">Click on me!</lable>
<div id="checkboxStatus">Off</div>

$('#checkboxId').change(() => {
    if($('#checkboxId').is(':checked')) {
        $('#checkboxStatus').text('Active')
    } else {
        $('#checkboxStatus').text('Inactive')
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<label><input type="checkbox" id="checkboxId">Click on me!</lable>
<div id="checkboxStatus">Off</div>

不必了 2024-12-05 22:17:50

通过名称获取无线电值

 $('input').on('className', function(event){
        console.log($(this).attr('name'));
        if($(this).attr('name') == "worker")
            {
                resetAll();                 
            }
    });

get radio value by name

 $('input').on('className', function(event){
        console.log($(this).attr('name'));
        if($(this).attr('name') == "worker")
            {
                resetAll();                 
            }
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文