Jquery:点击动作前确认

时间:2016-11-14 18:02:42

标签: javascript jquery ruby-on-rails

我的表单中有一个复选框。我想在检查包装盒之前询问用户确认。但是,在确认框被勾选后,“确认”消息会自动出现。我想这样做,以便用户可以“取消”,就好像他从未检查过盒子一样。

这是我的代码:

$( document ).ready(function() {
  $('.checkme').click(function(){
    text_area_id = "#" + $(this).val();
    if ($(text_area_id).attr('hidden')) {
      $(text_area_id).attr('hidden', false);
    } else{
      if ($(text_area_id).val() != '') {
        if (confirm("Clear text for \'" + $(this).val().replace(/_/g, " ") + "\'?")) {
          $(text_area_id).attr('hidden', true);
          $(text_area_id).val('');
          $(this).attr('checked', true);
          $('.checkme').attr('checked', true);
        }
      } else {
        $(text_area_id).attr('hidden', true);
        $('.checkme').attr('checked', true);
      }
    }
  });

请注意“确认”框。我希望点击复选标记框时出现 - 但实际上勾选了该框。

所以我猜我正在寻找像

这样的jquery函数
.before_click(function(){ ...

而不是

.click(function(){ ...

或类似的东西......?

1 个答案:

答案 0 :(得分:2)

只需根据confirm boolean值设置复选框的选中属性即可。 window.confirm会返回truefalse



$(".checkme").on('click',function(e){
  var r = confirm("Are you sure?!");
  $(this).attr('checked',r);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="checkme"/>Check me
&#13;
&#13;
&#13;

相关问题