AmberB AmberB -4 years ago 108
HTML Question

creating an alert that shows when form is submitted

I'm trying to create a function in javascript that gets an alert to show up when you click the submit button. I managed to get the alert to show but it only pops up when you open the page but doesn't work when you click the submit button.
heres the function i created in javascript

function orderTics(){
//creates alert
var orderTotal=35;

alert("Your order total is $"+orderTotal);


I called the function in html like this:


I'm still very much a beginner so any and all tips will be greatly appreciated

Answer Source

You could use the on submit function like this:

$("form.class-name").on("submit", function() {
  alert("I've been submitted.");

Vanilla JS onsubmit event:

document.querySelector("form.class-name").addEventListener("submit", function() {
  alert("I've been submitted.");
}, false);

You can also use the event.preventDefault(); method to prevent the form from going to another page, like this:

$("form.class-name").on("submit", function(event) {
  alert("Do stuff");

Vanilla JS onsubmit event with event.preventDefault(); method:

document.querySelector("form.class-name").addEventListener("submit", function(event) {
  alert("I've been submitted.");
}, false);

NOTE: when you use the event.preventDefault(); method the form won't redirect to the target page, even if you click the ok button in the alert box.

Finally you can just use the click event on the submit button, like this:

$("button.submit-button-class").on("click", function() {
  alert("I've been clicked!");

Vanilla JS onclick event:

document.querySelector("button.submit-button-class").addEventListener("click", function() {
  alert("I've been clicked!");
}, false);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download