L84
L84

Reputation: 46308

Call Custom Function on Form Submit

I have a function to swap data-attribute and action in a form:

$(function() {
    function SwapAction() {
        var dataAttr = $('.review-form').data();
        $('.review-form')[0].action = dataAttr.action;
    }
});

I want to do this upon submission of the form if the form passes validation checks. The validation JS looks like so:

var submitcount7303 = 0;

function checkWholeForm7303(theForm) {
  var why = "";
  if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, "First Name");
  if (theForm.LastName) why += isEmpty(theForm.LastName.value, "Last Name");
  if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value);
  if (why != "") {
    alert(why);
    return false;
  }
  if (submitcount7303 == 0) {
    submitcount7303++;
    SwapAction(); //Calling Function 
    theForm.submit();
    return false;
  } else {
    alert("Form submission is in progress.");
    return false;
  }
}

The form doesn't submit and I receive an error:

Reference Error: SwapAction is not defined.

Here is the form HTML with the action:

<form action="" data-action="/FormProcessv2.aspx?WebFormID=89926&amp;OID={module_oid}&amp;OTYPE={module_otype}&amp;EID={module_eid}&amp;CID={module_cid}" enctype="multipart/form-data" onsubmit="return checkWholeForm7303(this)" method="post" name="catwebformform7303" class="review-form custom">

I assume I am overlooking something simple. If I remove SwapAction(); and remove the data-action and set the form back to default it works without a problem.

How do I fix the error and implement my script?

Upvotes: 0

Views: 502

Answers (3)

Bhushan
Bhushan

Reputation: 6181

SwapAction() is out of scope here.

If you want to use your first approach:

$(function() {
SwapAction = function {
    var dataAttr = $('.review-form').data();
    $('.review-form')[0].action = dataAttr.action;
}
});

And then you can call it as you are calling in your current code.

Upvotes: 1

xdazz
xdazz

Reputation: 160843

You define SwapAction() in the callback function of document ready, that's a different scope, so you can't access it in global scope.

Upvotes: 1

adeneo
adeneo

Reputation: 318202

The function is not in scope, it's within the scope of the wrapping DOM ready function, so remove that :

function SwapAction() {
    var dataAttr = $('.review-form').data();
    $('.review-form')[0].action = dataAttr.action;
}

Upvotes: 1

Related Questions