Miss_sunshine
Miss_sunshine

Reputation: 107

javascript to jquery transition

I have a problem with jquery after converting javascript function to jquery

This is how my function looked alike in javascript code:

document.getElementById('checkoutForm').onsubmit = function () {
    var x = $("#checkbox-checkout").is(":checked");
    if (!x) {
        alert("Please indicate that you have read and agree to the Terms and Conditions");
        return false;
    }
};

jQuery

$("#checkoutForm").on("submit", function () {
    validateTerms();
});

validateTerms: function () {
var x = $("#checkbox-checkout").is(":checked");
if (!x) {
    alert("Please indicate that you have read and agree to the Terms and Conditions");
            return false;
}

HTML:

<div id="checkout-checkbox">
    <input type="checkbox" id="checkbox-checkout">   
</div>
<form method="post" id="checkoutForm">
    <button type="submit" class="btn btn-green btn-pay">PAY nOW</button>       
</form>

do you know what could cause not even calling the function? Do you see anything wrong? What could be the correct way of doing this?

Upvotes: 0

Views: 50

Answers (2)

user2575725
user2575725

Reputation:

Below line has an error, in-appropriate use of object notation.

validateTerms: function () {

Option 1:

var validateTerms = function () {
    // to do rest
    // return true or false
};

Option 2:

$("#checkoutForm").on("submit", function () {
   var x = $("#checkbox-checkout").is(":checked");
   if (!x) {
       alert("Please indicate that you have read and agree to the Terms and Conditions");
       return false;
   }
});

Option 3:

function validateTerms () {
    // to do rest
    // return true or false
}

For Option 1 & 3, you need to use functions as below:

$("#checkoutForm").on("submit", validateTerms);

OR

$("#checkoutForm").on("submit", function() {
   return validateTerms();
});

Upvotes: 1

tejashsoni111
tejashsoni111

Reputation: 1405

$("#checkoutForm").on("submit", function () {
    return validateTerms();
});

Here you are calling a function validateTerms(); to validate your form. Now this function returns you true or false based on the validation.

So to decide weather form should be submitted or not you need to return true or false from the submit event.

Upvotes: 1

Related Questions