2016-11-14 98 views
0

我的表單中有一個複選框。我想在用戶選中框之前詢問用戶。然而,在框勾選後,「確認」消息自動出現。我想讓它成爲用戶可以「取消」的狀態,就好像他從未選中過該盒子一樣。Jquery:在點擊動作之前確認

這裏是我的代碼:

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

注 「確認」 對話框。我希望在點擊複選框後出現 - 但在盒子實際上被打勾。

所以我想我正在尋找像

.before_click(function(){ ... 

,而不是

.click(function(){ ... 

或類似的東西一個jQuery函數...?

回答

2

只需根據您的confirmboolean值設置複選框的選中屬性。 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