How to enable / disable html button based on scripts?

I have a button on my webpage with the code below -

HTML:

<button type="submit" class="checkout-button" id="checkout-button" name="checkout-button"></button>

CSS

.checkout-button{
width: 130px;
height: 35px;
background: url('../poc2/images/checkout.png') no-repeat;
border: none;
vertical-align: top;
margin-left:35px;
cursor:pointer;
}

Now the button works fine, as I can click on it and execute my corresponding PHP code; the pointer turns into a hand symbol, allowing the user to clearly know that he is available for a click and that his button.

What I would like to do is change the behavior of this button based on some conditions. Pseudo-code example:

if flag=1: 
    /* enable the button, and let the user click it and run the php code */
else: 
    /* display this button, but don't let any actions take place if the user clicks on it; */

How do I encode this on-off logic for a button? Basically, I want the button to work like a button in normal situations; and just like an image without any hyperlink in some other situations.

+5
source share
3

JavaScript ( ) JavaScript .

:

<button type="submit" class="checkout-button" id="checkout-button" name="checkout-button" disabled="disabled"></button>

CSS, :

http://jsfiddle.net/Rgsen/14/

+8

action form. , "", .

+2

, / .

<button disabled="true"> <button disabled="false">

javascript :

if flag=1: 
    document.getElementById("your-btn").disabled = true;
else: 
    document.getElementById("your-btn").disabled = false;

jquery, :

if flag=1: 
    $('#your-btn').prop('disabled', true);
else: 
    $('#your-btn').prop('disabled', false);

/

css:

.btn-disabled{
    cursor: not-allowed;
    pointer-events: none;
}

/ .

jquery:

if flag=1: 
    $('#your-btn').addClass('btn-disabled');
else: 
    $('#your-btn').removeClass('btn-disabled');

If you don't need jquery but pure javascript, here 's how to do it.

+1
source

All Articles