简体   繁体   中英

Jquery: confirm before click action

I have a checkbox in my form. I want to ask the user for confirmation before he checks the box. However, the "confirm" message automatically comes up AFTER the box gets ticked. I want to make it so the user can "cancel", and it's as if he never checked the box to begin with.

Here's my code:

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

Note the "confirm" box. I want that to come up upon clicking the checkmark box -- but BEFORE the box actually gets ticked.

So I'm guess I'm looking for a jquery function like

.before_click(function(){ ...

instead of

.click(function(){ ...

Or something like that...?

Just set the checked attribute of checkbox based on your confirm boolean value. window.confirm returns true or false

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM