How to enable/disable an html button based on scenarios?

前端 未结 3 1692
终归单人心
终归单人心 2021-02-20 05:58

I have a button in my webpage with below code -

HTML:

相关标签:
3条回答
  • 2021-02-20 06:39

    You can do it either by modifying the attribute or by adding/removing a class.

    Modifying attribute

    You will want to switch between <button disabled="true"> and <button disabled="false">

    With javascript, it could look like this:

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

    And with jquery, like this:

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

    Adding/removing class

    Add the following css:

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

    And add/remove a class to the button.

    With jquery:

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

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

    0 讨论(0)
  • 2021-02-20 06:45

    If your circumstance allows you could just remove the content in the action attribute from the form tag. Therefor when a user clicks submit, no action is taken.

    0 讨论(0)
  • 2021-02-20 06:46

    You can either do this without JavaScript (requires a page refresh) or with JavaScript and have no refresh.

    Simply use the disabled attribute:

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

    And create a css style for it, if necessary. The example below shows a JavaScript solution. If the variable disableButton is set to true, the button will be disabled, else it can be clicked:

    const disableButton = true; //change this value to false and the button will be clickable
    const button = document.getElementById('checkout-button');
    
    if (disableButton) button.disabled = "disabled";
    .checkout-button {
      width: 130px;
      height: 35px;
      background: #333;
      border: none;
      vertical-align: top;
      margin-left: 35px;
      cursor: pointer;
      color: #fff;
    }
    
    .checkout-button:disabled {
      background: #999;
      color: #555;
      cursor: not-allowed;
    }
    <button type="submit" class="checkout-button" id="checkout-button" name="checkout-button">submit</button>

    0 讨论(0)
提交回复
热议问题