x13
x13

Reputation: 2237

Prevent <button> being clicked without disabling it

On my page i have a <button> with an <input type="number" /> inside, when a user clicks in the <input> or it's spinner buttons the <button>'s click event will fire and the <button> obtains the :active style. Setting <button disabled="disabled"> does prevent click event from firing but the <button> obtains the disabled style.

What i am looking for is how to make the <button> unclickable using simple Javascript, CSS, or HTML without hijacking click events, disabling it, or putting something transparent on top. It should appear normal but when clicked it must not change style or fire a click event.

What i have http://jsfiddle.net/tzu8gLvm/

Upvotes: 4

Views: 5525

Answers (3)

x13
x13

Reputation: 2237

I solved it myself after some experimenting. the reason why i didn't want to disable my <button> was that it will look disabled. Apparently the :disabled style can be overridden with button:disabled { color: black; }, this makes it perfectly acceptable for me to disable it.

function disable(id) {
  document.getElementById(id).disabled = 'disabled';
}

function enable(id) {
  document.getElementById(id).removeAttribute('disabled');
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  opacity: 1;
}
#orderbutton3:disabled {
  color: black;
}
Begin (clicking the number input clicks the button) :
<br/>
<button id="orderbutton1" type="button">
  Order&nbsp;
  <input type="number" style="width: 38px;" name="amount" min="0" value="0" max="999">
  <b>&times;</b >
  &nbsp;
</button >
<br/>
<hr/>
This is what i get when i just disable it :
<br/>
<button id="orderbutton2" type="button">
  Order&nbsp;
  <input type="number" onmouseover="disable('orderbutton2');" onmouseout="enable('orderbutton2');" style="width: 38px;" name="amount" min="0" value="0" max="999">
  <b>&times;</b >
  &nbsp;
</button >
<br/>
<hr/>
What i ended up with (clicking the input does not click the button and the button appears clickable because i have overridden the text color) :
<br/>
<button id="orderbutton3" type="button">
  Order&nbsp;
  <input type="number" onmouseover="disable('orderbutton3');" onmouseout="enable('orderbutton3');" style="width: 38px;" name="amount" min="0" value="0" max="999">
  <b>&times;</b >
  &nbsp;
</button >

Upvotes: 0

Touffy
Touffy

Reputation: 6561

Your restrictions cover a lot of good solutions. What's wrong with disabled??

But as it happens, there is a CSS way. You can set pointer-events: none on the input, and clicks will just pass through.

Upvotes: 2

Ehsan
Ehsan

Reputation: 4474

You should use the preventDefault() function in javascript to prevent an action to be fired. Take a look at this link.

Upvotes: 0

Related Questions