In order to control the input format in the ZIP code field in the dynamic address fields provided by the Address Field module (I use it in Drupal Commerce) I need to add the attributes onKeyUp
and onBlur
to this field. My plan is to use Javascript to manage the formatting, but I need to add the above attributes first. How do I do that? I imagine I should use hook_form_alter
in my template.php, but I could need a pointer on how to do it.
if($form['#id'] === "edit-customer-profile-billing-commerce-customer-address-und-0-postal-code"){
dsm($form); // devel message does not show up in the checkout page in question
$form['#attributes']['onBlur'] = '(this)';
}
EDITED: I have now managed to add the attributes this way:
function mytheme_form_alter(&$form, &$form_state, $form_id) {
if($form_id === "commerce_checkout_form_checkout"){
// Merge new attributes with existing ones.
$form['customer_profile_billing']['commerce_customer_address']['und']['0']['locality_block']['postal_code']['#attributes'] = array(
'onBlur' => 'setZip(this)',
'onKeyUp' => 'setLimit(this,5)',
);
$form['customer_profile_shipping']['commerce_customer_address']['und']['0']['locality_block']['postal_code']['#attributes'] = array(
'onBlur' => 'setZip(this)',
'onKeyUp' => 'setLimit(this,5)',
);
}
}
And this is the js script (I found it here):
(function($) {
$(document).ready(function(){
'use strict';
var setZip, setLimit;
console.log('outside');
function setZip(theField){
console.log('setzip');
var num = theField.value.replace(/\D/g,"");
theField.value = num.substr(0,3)+" "+num.substr(2);
}
function setLimit(theField, maxDigit){
console.log('setlimit');
var num = theField.value.replace(/\D/g,"");
if(num>maxDigit){
theField.value = theField.value.substr(0,maxDigit);
}
}
});
})(jQuery);
The problem now is that I get a javascript reference error like this:
Uncaught ReferenceError: setZip is not defined at HTMLInputElement.onblur
I suspect this has something to do with the scope, so I have tried to place the js script with the setLimit and setZip functions in the header, in the body and in the footer, with the same error message. I also tried to remove the $(document).ready(function()
... but the reference error reamins.
Any ideas?
$form_id
param, use that to work out what the correct value is