Enter Key on Coupon Field Tutorial
This brief tutorial will show you how to use jQuery to tune up some form behavior in the single page checkout. The problem with the ENTER key within browsers is that the spec doesn't really make it clear how every single browser will treat things:
User agents may establish a button in each form as being the form's default button. This should be the first submit button in tree order whose form owner is that form element, but user agents may pick another button if another would be more appropriate for the platform. If the platform supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so must cause the form's default button's activation behavior, if any, to be run.
UltraCart tries to put a hidden harmless submit button that will just perform an update at the top of the single page checkout, but alas the part of the spec that says "user agents may pick another button" could be problematic. We should be able to use some JavaScript to tell the browser that if they hit ENTER in this particular field then we want to click a very specific submit button on the page.
So the first thing we will do is add jQuery to our screen branding. This code is pretty generic and should work in versions of jQuery from 1.4.X up to the latest.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Now we need to attach a key press handler to the coupon code entry field and then give it logic to click the apply coupon submit button.
<script type="text/javascript"> jQuery(document).ready(function() { jQuery('input[name="couponCode"]').keypress(function (e) { var code = e.keyCode || e.which; if (code === 13) { e.preventDefault(); jQuery("#APPLY_COUPON").click(); } }); }); </script>
Let's take a moment to dissect what this JavaScript code is doing:
- When the document is ready
- Find the input field named "couponCode" (this is no ID on this field presently so we'll reference by name)
- Attach a keypress handler to the input field
- Each time a key is pressed look for code 13 (enter key)
- If code 13 is pressed prevent the default behavior from happening (this will keep the browser from submitting how it would normally want to)
- Find the apply coupon button (which has an ID of APPLY_COUPON) and click it.
Â