I'm in the process of developing a form where the user enters a UK postcode and the textfield is replaced by a select list. This all works quite nicely when using the blur event, but it is not always obvious the field has changed.

I would like to use the keyup event instead, but there is a small delay each time the key is pressed as the AJAX keeps firing, I have an existing function which is bound to the field:

$('#edit-postcode').bind('input', function(){
  $(this).val(function(_, v){
    return v.replace(/\s+/g, '').toUpperCase();

I already have a simple regex /(^[A-Z]{1,2}[0-9]{1,2})\s?([0-9][A-Z]{2}$)/i to ensure it's broadly the correct format. I would like to add the validation into the previous function and if the string passes validation trigger the existing AJAX functionality.

N.B. the default Drupal autocomplete functionality works almost perfectly apart from not being able to hide the ID which relates to the postcode which is why I've resorted to this method instead.

  • try using this combo 'event' => 'change', 'keypress' => TRUE, – No Sssweat May 1 '19 at 8:25
  • Still pretty much the same as the blur event, but doesn't answer my actual question – Colin Shipton May 1 '19 at 15:13

It turns out that it's actually much easier than I thought, by using a custom jQuery event, in my case I called in postcodeValid:

'#ajax' => [
  'callback' => [$this, 'checkPostcode'],
  'event' => 'postcodeValid',
  'wrapper' => 'postcode-container',

I changed the JavaScript function I already had to:

$('#edit-postcode').bind('input', function() {
  var trigger = $(this);
  $(this).val(function(_, v) {
    if (isValidPostcode(v)) {
    return v.replace(/\s+/g, '').toUpperCase();

The isValidPostcode function is a simple test against my postcode regex, thanks to Delay ajax call on textfield to allow for typing I was able to discover this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.