Alex Alex - 1 month ago 11
PHP Question

Javascript to trigger an alert message on a form

I have a PHP page with a form:

<form method="POST" action="multimod.php" id="multiple">
<!-- some checkboxes here -->
<input type="image" name="submit" src="img/upd.png" alt="modify" class="multi" />
</form>


Then I want to trigger an alert on submit. When the image is clicked on, a sweetAlert message is triggered:

<script>
$('input.multi').click(function(e){
e.preventDefault();
swal({
title: "a title",
text: "some text",
type: "warning",
confirmButtonText: 'yes',
cancelButtonText: 'no',
showCancelButton: true,
},
function(){
document.forms["multiple"].submit();
});
});
</script>


As you can see the
id
of the form ("multiple") is used to reference it in the Javascript function.

It works for me, but I wonder if the syntax of the script is actually correct. I found this workaround online, and maybe there are better ways of doing it.

Answer

Since you want to trigger it on submit, there is no reason to add a listener on the button.

<script>
function onFormSubmit() {
  alert("Before submitting to server!");
  return true; // allow the submission!
}
</script>
<form onsubmit="return onFormSubmit();" method="POST" action="multimod.php" id="multiple">
  <!-- some checkboxes here -->
  <input type="image" name="submit" src="img/upd.png" alt="modify" class="multi" />
</form>