如何根据情况启用/禁用html按钮? [英] How to enable/disable an html button based on scenarios?

查看:330
本文介绍了如何根据情况启用/禁用html按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上有一个带有以下代码的按钮-

I have a button in my webpage with below code -

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;
}

现在,该按钮可以正常工作,因为我可以单击它并运行相应的php代码;指针变成手形符号,使用户清楚地知道它是可单击的,并且是按钮.

Now, the button works fine as I can click on it and have my corresponding php code run; the pointer turns into the hand symbol letting the user clearly know that it is clickable and that its a button.

我想做的是根据某些条件修改此按钮的行为.伪代码示例:

What I would like to do is to modify the behavior of this button based on some conditions. Example pseudocode:

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 code this enable-disable logic for the button? Basically, I want the button to work as a button under normal situations; and just as a picture without any hyperlink under certain other situations.

推荐答案

您可以在没有JavaScript(需要刷新页面)或没有JavaScript的情况下执行此操作.

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

只需使用disable属性:

Simply use the disabled attribute:

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

并根据需要创建css样式.下面的示例显示了一个JavaScript解决方案.如果变量disableButton设置为true,则该按钮将被禁用,否则可以单击:

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>

这篇关于如何根据情况启用/禁用html按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆