views:

40

answers:

2

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&amp;i=770678&amp;cl=122992&amp;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>
A: 

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();
    }
});
Matchu
A: 

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&amp;i=770678&amp;cl=122992&amp;ejc=2"  method="POST" onSubmit="return function(e)" target="ej_ejc" accept-charset="UTF-8">
GetAwesome
I do apologize for these simple questions. I'm still quite a newbie at javascript/jquery.
GetAwesome
Your form has the `target` attribute, which would cause it to open in a new tab with the internal name "ej_ejc". You should probably only have that if you really want it there. Also, on SO, when an answer answers your question, be sure to click the check mark next to it, so the poster gets credit :) Thanks!
Matchu
Will definitely do. Thanks for the heads up!
GetAwesome