如果确认提示false,则从复选框中删除勾选

时间:2013-11-10 08:15:14

标签: jquery html

我正在使用此HTML:

<tr>
  <td class="smalltext" width="100%">
     <label>
       <input type="checkbox" value="1" name="guarantee" id="guarantee_check_tick" />
       &mdash; Tick this checkbox if you are going to give 100% satisfaction guarantee.
     </label>
  </td>
</tr>

和jQuery:

jQuery(document).ready(function($)
{
    $("#guarantee_check_tick").click(function()
    {
        var $this = $(this);
        if ($this.is(":checked"))
        {
            confirm('Are you sure you are going to provide 100% satisfaction guarantee?');
        }
    });
});

现在它做了什么,当用户点击复选框时,确认显示(这很好),当用户点击“确定”按钮时勾选复选框,如果用户点击“取消”按钮(确认提示) )然后复选框应保持未勾选状态。我怎样才能做到这一点?

请帮忙!

3 个答案:

答案 0 :(得分:4)

confirm方法返回布尔值。检查它是真还是假并执行。

试试这个:

$(document).ready(function()
{
    $("#guarantee_check_tick").change(function() // changed from click to change
    {
        var $this = $(this);
        if ($this.is(":checked"))
        {
            if(confirm('Are you sure you are going to provide 100% satisfaction guarantee?') == true){
                //your code
            }
            else{
                $this.removeAttr("checked");
            }
        }
    });
});

Fiddle here.

答案 1 :(得分:3)

工作演示 http://jsfiddle.net/88LHL/

Doc:https://developer.mozilla.org/en-US/docs/Web/API/Window.confirm

这符合您的需求:)

<强>代码

jQuery(document).ready(function ($) {
    $("#guarantee_check_tick").click(function () {
        var success = false;
        var $this = $(this);
        if ($this.is(":checked")) {
            success = confirm('Are you sure you are going to provide 100% satisfaction guarantee?');
        }


        if (success == true) {
            alert('Changed');

            // do something                  
        } else {

            alert('Not changed');
            $this.prop('checked', !$this.prop('checked'));
            // Cancel the change event and keep the selected element
        }

    });
});

答案 2 :(得分:2)

你能试试吗,

    jQuery(document).ready(function($)
    {
        $("#guarantee_check_tick").click(function()
        {
            var $this = $(this);
            if ($this.is(":checked"))
            {
                var r = confirm('Are you sure you are going to provide 100% satisfaction guarantee?');
                     // r value is either true or false

                if(!r){
                    $this.attr('checked', false);
                }
            }
        });
    });