Manually trigger AJAX from custom JavaScript 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.
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' =&gt; [
  'callback' =&gt; [$this, 'checkPostcode'],
  'event' =&gt; 'postcodeValid',
  'wrapper' =&gt; '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)) {
      trigger.triggerHandler('postcodeValid');
    }
    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.