Reputation: 25239
I just noticed a weird behavior:
I want to dynamically disable a element to prevent a user to open the options menu, but at the same time I want to bind a click, so the user when clicks it, it will receive an alert "sorry this selector is disabled"
a better example can be, say, when you have two select elements, and if the user chooses an option from #select1, it's forbidden to choose anything form #select2
I don't want to hide the #select2 for other reason I don't need to fully explain.
<form>
<select id="select1" disabled> // jquery on() won't work because of "disable"
<option value='1' >apple</option>
<option value='2' >banana</option>
</select>
</form>
$('form').on('click', '#select1', function(e){
// do something
});
Upvotes: 0
Views: 1135
Reputation: 46
You can't bind to a disabled field in javascript. Your options would be to make a div around the select to receive the click events as mentioned by Alex, or if you really don't want additional elements, you can leave the select box enabled, style it to look disabled, and immediately blur on click. This isn't a very clean solution but I don't know what your restrictions are as far as adding elements goes.
$("#select1").click(function(){
$(this).blur();
});
.disabled{
color: #bababa;
background-color: #f0f0f0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="select1" class="disabled">
<option value='1' >apple</option>
<option value='2' >banana</option>
</select>
</form>
Upvotes: 1
Reputation: 2232
Here's a workaround solution to your problem.
You can overlay a div
over the select and upon loading, check if it disabled
if it is NOT disabled
, we use .remove()
to remove the overlay, otherwise, we keep it there to hook a .on('click'...)
event onto it.
let disabled = $('#select1').is(':disabled')
if (!disabled) {
$('#test').remove();
}
$('#test').on('click', function(e) {
alert("sorry this selector is disabled");
});
#test {
position: absolute;
width: 68px;
height: 17px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="test"></div>
<select id="select1" disabled>
<option value='1'>apple</option>
<option value='2'>banana</option>
</select>
</form>
Upvotes: 0