Search code examples
javascriptbuttonsubmitconfirmation

Change the text of submit button when clicked OKAY on alert pop-up


I have a shopping cart system where a customer can take orders and check out if they have anything on the cart but can't continue if it has nothing.

An alert will pop-up if they click on Submit button. I have this javascript for that one.

function validateForm()
{
var x=document.forms["form1"]["total"].value;
if (x==null || x=="")
  {
  alert("Take your order first.");
  return false;
  }
var con = confirm("Are you sure you want to order this item/s?");
if (con ==false)
{
return false;
}
}

How can I change the text of the submit button when the Okay is clicked on the pop-up message? Instead of "Add Order" I want it to be changed to "Update order" when the customer added his/her order once.


Solution

  • You mean this?

    document.getElementById("myForm").addEventListener("submit",function(e) {
      var x = this.total.value.trim(), sure = false;
      if (this.subBut.value=="Update order" && x !=="") return true;
      e.preventDefault();
      if (x == "") {
        alert("Please take your order first.");
      }
      else sure =  confirm("Are you sure you want to order this item/s?");
      if (sure) {
        this.subBut.value="Update order";
      }
      return sure;
    });
    <form id="myForm">
    <input type="text" name="total" value="" />
    <input type="submit" name="subBut" value="Add order" />
    </form>