GetAwesome
GetAwesome

Reputation: 3

Disable a form 'action' if jquery validation fails

I'm trying to finalize my webpage's shopping cart and I'm running into one final problem. There is a text box next to my 'add to cart' button that requires a specific hardware key (Fingerprint) to be entered before completing the purchase. I need to set it up so that the end-user cannot click "add to cart" until that field is validated.

I have successfully setup the validation to make the text box required and only allow a specific string of characters, but I can't seem to figure out how to dynamically 'disable' the form action until the text box is successfully validated.

Here is my jquery:

<script>
$(document).ready(function() {

$.validator.addMethod("os0", function(value) {
    return /^(([a-fA-F0-9]{4,4})+\-([a-fA-F0-9]{4,4}))$/.test(value); 
    }, "Invalid Fingerprint.");     

$("#myFingerprint").validate({  
     rules: {
        os0: "required os0",
    },      
  });
});
</script>

Here is the corresponding HTML: (the form code is copy&pasted from our e-commerce provider)

<td>                                                            
 <form id="myFingerprint" action="https://www.blahblahblah.com/ecom/gb.php?c=cart&i=770678&cl=122992&ejc=2" target="ej_ejc" method="POST" accept-charset="UTF-8">

 <input type="hidden" name="on0" value="Fingerprint"/>

Fingerprint:<br/>

<input type="text" id="os0" name="os0" maxlength="9"/>

<input type="image" src="http://www.blahblahblah.com/add_to_cart.gif" border="0" alt="Add to Cart" class="ec_ejc_thkbx" onClick="javascript:return EJEJC_lc(parent);"/>
 </form>
</td>

Upvotes: 0

Views: 4593

Answers (2)

GetAwesome
GetAwesome

Reputation: 3

Matchu, you are a life-saver. That worked like a charm.

I do have one strange occurrence though. With that script added, when a valid hardware key is entered and 'add to cart' is clicked, my shopping cart now opens in a new browser tab, rather than being a pop-up in the same window. Any ideas here? Just in case, my new html form code looks like this:

<form id="myFingerprint" action="https://www.e-junkie.com/ecom/gb.php?c=cart&i=770678&cl=122992&ejc=2"  method="POST" onSubmit="return function(e)" target="ej_ejc" accept-charset="UTF-8">

Upvotes: 0

Matchu
Matchu

Reputation: 85792

You can give a form an onsubmit method, and then have that cancel the form submission if the form is not validated.

$('#myFingerprint').submit(function (e) {
    if(!all_of_my_validation_passed) {
        e.preventDefault();
    }
});

Upvotes: 2

Related Questions