I've a checkbox that enable or disable a select element
Actually I use this simple piece of code that works fine.
$("#filtri").change(function(){
if ($("#menuContinenti").attr("disabled")) {
$("#menuContinenti").removeAttr("disabled");
} else {
$("#menuContinenti").attr("disabled", "disabled");
}
});
Is this the best way or is there something like a .toggle()
function to switch between disabled/enabled?
To remove disabled attribute using jQuery, use the removeAttr() method. You need to first remove the property using the prop() method. It will set the underlying Boolean value to false.
To remove the disabled attribute, select the element and call the removeAttribute() method on it, passing it disabled as a parameter, e.g. btn. removeAttribute('disabled') . The removeAttribute method will remove the disabled attribute from the element.
To set the disabled attribute, select the element and call the setAttribute() method on it, passing it disabled as the first parameter, e.g. button. setAttribute('disabled', '') . The setAttribute method will add the disabled attribute to the element.
You can use $(":disabled") to select all disabled items in the current context. To determine whether a single item is disabled you can use $("#textbox1").is(":disabled") .
You should use .prop
for disabled:
$("#menuContinenti").prop('disabled', function () {
return ! $(this).prop('disabled');
});
UPDATE: didn't realize the current property value is an argument to the function; this version is even cleaner:
$("#menuContinenti").prop('disabled', function (_, val) { return ! val; });
UPDATE: ES2015
$("#menuContinenti").prop("disabled", (_, val) => !val);
You can write your own plugin that does something like this.
Add this after jQuery, in a script file preferably.
(function($) {
$.fn.toggleDisabled = function(){
return this.each(function(){
this.disabled = !this.disabled;
});
};
})(jQuery);
Then use it like this:
$('#my-select').toggleDisabled();
Courtesy: Toggle input disabled attribute using jQuery
you can check using $.is function like below
$("#filtri").change(function(){
$("#menuContinenti").attr("disabled", ! $(this).is(':checked'));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With