A2oz

How to disable a button in jQuery Mobile?

Published in Web Development 2 mins read

You can disable a button in jQuery Mobile using the disabled attribute for form buttons and by adding the ui-state-disabled class to link buttons.

Disabling Form Buttons

For buttons created using the <button> or <input> elements, simply add the disabled attribute to disable them:

<button disabled>Disabled Button</button>
<input type="submit" disabled value="Submit">

You can also use jQuery to dynamically disable form buttons:

$('#myButton').prop('disabled', true);

Disabling Link Buttons

For buttons created using anchor tags (<a>), the disabled attribute doesn't work. Instead, add the ui-state-disabled class to disable the button:

<a href="#" class="ui-state-disabled">Disabled Link Button</a>

You can also use jQuery to dynamically disable link buttons:

$('#myLinkButton').addClass('ui-state-disabled');

Enabling Buttons

To enable a disabled button, simply remove the disabled attribute (for form buttons) or the ui-state-disabled class (for link buttons):

$('#myButton').prop('disabled', false);
$('#myLinkButton').removeClass('ui-state-disabled');

Examples

Here are some practical examples:

  • Disabling a button after a form submission: You can disable the submit button after the form is submitted to prevent multiple submissions:
$('#myForm').submit(function() {
    $('#submitButton').prop('disabled', true);
});
  • Disabling a button while loading data: You can disable a button while loading data to prevent users from clicking it multiple times:
$('#myButton').prop('disabled', true);
$.ajax({
    // ...
    success: function() {
        $('#myButton').prop('disabled', false);
    }
});
  • Disabling a button based on user input: You can disable a button based on user input, such as only enabling it if a specific field has been filled in:
$('#myField').on('keyup', function() {
    $('#myButton').prop('disabled', $(this).val() === '');
});

Related Articles