简体   繁体   中英

Delete Confirmation

I have a set of records which are displayed in tabular format in a form. On each record there is a delete checkbox - here is the form in simplified format:

<form method="post" action="" id="update-history-form">
  Item 1 <input type="checkbox" value="1" name="History[0][delete]">
  Item 2 <input type="checkbox" value="1" name="History[1][delete]">
  Item 3 <input type="checkbox" value="1" name="History[2][delete]">

  <input type="submit" value="Update History" name="update">
</form>

The integer value in the input 'name' attribute helps identify which records have been selected for deletion.

What I want is for a JavaScript alert confirmation to appear if any of the delete checkboxes have been ticked (upon submit).

$('#update-history-form').submit(function(){
  if ( $(this).find('input:checkbox:checked').length ){
    return confirm( "Really delete any of them?" );
  }
});

This will cancel the form submission of the user does not OK the confirmation dialog.

If you have non-delete checkboxes in your form you may need to modify the selector to only those inputs whose name contains "delete", eg

$(this).find( 'input[name*="delete"]:checked' )

Using jQuery:

$('#update-history-form').submit(function(ev) {
  ev.preventDefault();
  if (this.find("input:checkbox:checked").length == 0 || confirm("Are you sure?")) this.submit();
});
<form method="post" action="" id="update-history-form" onsubmit='return confirmChecks(this);'>
  Item 1 <input type="checkbox" value="1" name="History[0][delete]">
  Item 2 <input type="checkbox" value="1" name="History[1][delete]">
  Item 3 <input type="checkbox" value="1" name="History[2][delete]">

  <input type="submit" value="Update History" name="update">
</form>
<script type='text/javascript'>
function confirmChecks(someForm) {
  var inputList = someForm.getElementsByTagName('input');
  var aCheckboxIsChecked = false;
  for (var i=0; i < inputList.length; i++) {
    if (inputList[i].type.toLowerCase() == 'checkbox' && inputList[i].checked) {
      aCheckboxIsChecked = true;
      break;
    }
  }

  if (aCheckboxIsChecked) {
    var proceed = confirm('Really delete those things?');
    if (!proceed) {
      return false;
    }
  }
  return true;
}
</script>

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