Tag Archives: jquery

Disabled submit buttons in Chrome

There is an interesting difference in the way Chrome handles disabled submit buttons that is worth keeping in mind when developing for different browsers.

disabled submit

When the user clicks a button — particularly a submit button — it is often useful to disable the button so the user can’t accidentally click it multiple times. Multiple clicks would lead to undesirable results, such as a blog post being submitted twice or, worse, a sales order being executed more than once.

Let’s consider an HTML form called my-form with a button named submit-button.

<form id="my-form">
    <!--Form elements would go here-->
    <button id="submit-button" type="submit">Submit</button>

The following JavaScript (which relies on jQuery) will work on non-Chrome browsers.

$('#submit-button').on('click', function (e) {
    $(this).attr('disabled', 'disabled');

This event is triggered when the submit-button is clicked. It sets the button’s disabled attribute. Afterwards, the browser will submit the form.

To get the above code to work in all browsers, make the following changes.

$('#submit-button').on('click', function (e) {
    $(this).attr('disabled', 'disabled');

The first line will disable the browsers default behavior (e.preventDefault();) — which is to submit the form. Then we disable the button like we did before. Finally, the form is submitted imperatively by the JavaScript.

Submitting a form using XHR and jQuery

jQuery’s serialize() method offers a convenient way to turn an HTML form’s data into a text string in standard URL-encoded notation. Consider the following code

$('form').on('submit', function(e) {
        type: 'POST',
        url:  '/my/endpoint',
        data: $('form').serialize(),
        dataType: 'json',
        success: function(data){
            // Success Code
        error: function(jqXHR, strStatus, strErrorThrown){
            // Error Code

This serializes the form data in $(‘form’) and sends it to /my/endpoint.

Note that the JSON will contain keys for all the input elements regardless of whether or not they contain data except for inputs of type “radio” or “checkbox”. They must be clicked, then their key and value will be present in the JSON.

The following PHP code will take the serialized form data and convert it into a standard PHP array.

$qry = file_get_contents("php://input");
parse_str($qry, $qry_array);

$qry_array will contain the form’s data.