Tag Archives: Forms

Triggering default Ajax behaviour in Drupal textfields for better UX

By default, the addressfield form elements triggers Ajax requests on change, which means textfields only triggers when blurred. This may leave the user wondering what to do if the next field depends on the results of the Ajax request. To trigger the default Ajax behaviour on other events, you can do


$('body').on('change keyup paste', '.selector.for.your.element', function(e) {
var current_value = $(this).val();
// Do some checks before the request.
if (current_value.length === 4){
// Blur the textfield.
$(this).trigger("blur");
return false;
}
});

A few notes:
on() is used so that the event is live. i.e. still bound after the element is updated, which is common in Ajax forms. If event listeners are added to the element directly, it is lost after the form is updated.

The events ‘change’, ‘keyup’, ‘paste’ is used to capture common events where the contents of the field might change.