7
  • I need to have an onclick event on an <input> tag which is disabled.
  • Here onclick event doesn't work.
  • Is there any other way to work with onclick event for disabled input based on id?
  • I tried the code below.
  • First input worked but I need worked same as second one also same as of first one. (I need to call function Clicked on input only).

My code:

function Clicked(event)
{
  alert(event.id)
}
function ClickedDisabled(event)
{
  alert(event.ids)
}
<input type="text" id="ID" onclick="Clicked(this)" />
<input type="text" id="IDs" onclick="ClickedDisabled(this)" disabled />
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Hydrogen
  • 167
  • 3
  • 10

2 Answers2

5

function Clicked(event) {
  alert(event.id)
}

function ClickedDisabled(event) {
  alert(event.id)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="text" id="ID" onclick="Clicked(this)" />
<span style="position:relative;">
<input type="text" id="IDs" disabled />
<div style="position:absolute; left:0; right:0; top:0; bottom:0; cursor: pointer;" id="IDs" onclick="ClickedDisabled(this)"></div>
  </span>

Try this it may help you

priya786
  • 1,804
  • 12
  • 11
1

Put

input[disabled] {pointer-events:none}

in your CSS (it prevents some browsers from discarding clicks on disabled inputs altogether), and capture the click on a parent element. It's a cleaner solution, IMHO, than putting a transparent overlay over the element to capture the click, and depending on circumstances may also be much easier than simply "simulating" the disabled state using CSS (since that won't prevent the input from being submitted, and also requires overriding the default browser 'disabled' style).

If you have multiple such buttons, you'll need a unique parent for each, in order to be able to distinguish which button was clicked, because with pointer-events:none, the click target is the button's parent rather than the button itself. (Or you could test the click coordinates, I suppose...).

If you need to support older browsers, though, do check which ones support pointer-events: http://caniuse.com/#search=pointer-events

Doin
  • 7,545
  • 4
  • 35
  • 37