ToddT
ToddT

Reputation: 3258

Assign a standard jQuery function to a variable

How can I assign these functions submit() and click() to a variable. So that I can use them in an if statement like this:

function sendToCheckout() {
  $(document).ajaxComplete(function(){
    if($("form[action='/cart']").length == 1){
      var x = submit();
    }
    else {
      var x = click();
    }
    $("form[action='/cart']").off().x(function(event){
      event.preventDefault(event);
      var amountToSend = sessionStorage.getItem('amountToSend');
        if(amountToSend != null && amountToSend != "0"){
          sendData();         
        }
        else{
          window.location.href = shopAddress + "/checkout";
        }      
    });
  });
}

With the above code I got the error Uncaught ReferenceError: submit is not defined

Upvotes: 0

Views: 51

Answers (1)

Barmar
Barmar

Reputation: 780724

These functions are also the names of events, so you can work with them that way.

Assign the event name as a string, then use .on(), which takes the event name as a parameter.

You also shouldn't have multiple var x declarations. Declare it before the if, then assign it in it.

function sendToCheckout() {
  $(document).ajaxComplete(function() {
    var x;
    if ($("form[action='/cart']").length == 1) {
      x = "submit";
    } else {
      x = "click";
    }
    $("form[action='/cart']").off().on(x, function(event) {
      event.preventDefault(event);
      var amountToSend = sessionStorage.getItem('amountToSend');
      if (amountToSend != null && amountToSend != "0") {
        sendData();
      } else {
        window.location.href = shopAddress + "/checkout";
      }
    });
  });
}

Upvotes: 2

Related Questions