Tuesday, April 05, 2016

Re-enable disabled disable_with fields

I have some forms that do JavaScript based validation before submitting to the server.  The submit button is using the disable_with construct, so when the submit button is pressed, it is correctly disabled, but when the client-side validation fails, it's stuck disabled.

To remedy this situation, I added these lines to the JavaScript code that hides the error messages after they've been displayed for 5 seconds.

// re-enable 'disable_with' fields after validation errors
var disabled_with = jQuery('[data-disable-with][disabled]');
if (disabled_with) {
    jQuery.rails.enableElement(disabled_with);
    disabled_with.val(function(){ return jQuery(this).text()}).prop('disabled', false);
}

The first line is the commonly proposed solution that I found elsewhere online, but when I tried it (in Chrome), I found that it didn't work, leaving the button disabled with the disabled text displayed. However, one important thing it did was to insert the original button text as HTML content of the input element.  I added the second line to use that text as the button value and then actually enable the button.