Javascript
How to keep a button disabled until the page is loaded
There are cases when you need to keep a button disabled until the page is rendered. The main reason you may need this is to prevent the user from clicking on a button that is not functional at that point.
The easiest way of achieving this is to follow these 2 steps:
- Disable the button from HTML:
123456<button id="add-to-cart"type="submit"value="Add to cart"class="button-large add-to-cart"disabled="disabled">Add to cart</button> - Enable the button from JavaScript when the page is loaded:
123456// Enable the add-to-cart button when the page is loaded$(window).load(function() {if ( $('#add-to-cart').length > 0 ) {$('#add-to-cart').prop('disabled', false);}});
That’s it!
Additional notes
Keep in mind that there might be situations when you’ll need to consider cases like the product is out of stock and the button should remain disabled. Or there is a quantity limit that cannot be exceeded for that product, so the button should be disabled when that limit is reached.
There are many other things that can influence the approach presented above (depending on what your button is doing), and a simple way of dealing with this is to add a class on the button in case some restrictions should be in place.
Then just check in JavaScript if the class is there, and don’t enable the button.
Example:
- Do some checks in the backend and set a boolean to determine if the button should remain disabled or not. Example: set a quantity limit.
1234//Some code goes hereif (quantityInCart >= purchaseLimit) {isAddToCartAllowed = false;} - Disable the button from HTML and add a class if you condition is met (quantity limit was reached):
123456<button id="add-to-cart"type="submit"value="Add to cart"class="button-large add-to-cart <if condition='${!isAddToCartAllowed}'>bd-disabled></if>"disabled="disabled">Add to cart</button> - Enable the button from JavaScript when the page is loaded and if the condition is not broken:
123456// Enable the add-to-cart button when the page is loaded only for the case the qty limit was not exceeded$(window).load(function() {if ( ($('#add-to-cart').length > 0) && !($('#add-to-cart').hasClass('bd-disabled')) ){$('#add-to-cart').prop('disabled', false);}});