0

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:

<script>
orderTics();
</script>

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

AmberB
  • 13
  • 1
  • 8

3 Answers3

2

You can use the below.

$("#FormSelector").on("submit", function() {
   //Your code goes here
});
jQuery
  • 21
  • 2
1

Call your function like this:

<input type="button" value="myButton" onclick="orderTopics();">
Stijn Westerhof
  • 474
  • 1
  • 6
  • 16
  • Don't use the `onclick` attribute (or any other event attribute for that matter) in your HTML, it's considered to be *bad practice*. For more info check out this answer: http://stackoverflow.com/a/5871830/5870134 –  Mar 23 '17 at 17:21
1

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) {
  even.preventDefault();
  alert("Do stuff");
});

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

document.querySelector("form.class-name").addEventListener("submit", function(event) {
  event.preventDefault();
  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);