Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a div is disabled jQuery

I need to check whether myDiv1 is disabled. If so, I need to hide myDiv2, otherwise I need to show myDiv2.

Here is what I have so far:

$(document).ready(function () {
    var isDisabled = $('#myDiv1').is('[disabled=disabled]')
    alert(isDisabled); //this always returns false
    if(isDisabled)
        $("#myDiv2").hide();
    else
        $("#myDiv2").show()
});

But isDisabled return always false even when myDiv1 is enabled. What am I missing here?

like image 645
Pissu Pusa Avatar asked Jan 19 '17 07:01

Pissu Pusa


People also ask

How do you know if an element is disabled?

Use the disabled property to check if an element is disabled, e.g. if (element. disabled) {} . The disabled property returns true when the element is disabled, otherwise false is returned. Here is the HTML for the examples in this article.

How do you check checkbox is enabled or not in jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

Can I disable div in jQuery?

Using jQuery The idea is to disable click events inside div with jQuery and CSS. This can be done by setting pointer-events CSS property with the help of jQuery's . addClass() function.


1 Answers

So many answers, but none addressing the actual problem: A div element doesn't allow an attribute of type disabled. On a div only global attributes are allowed, whereas disabled is allowed on form elements.

You can easily verify it by testing this HTML:

<div id="a" disabled></div>
<input id="b" disabled>

against this JavaScript:

var e = $('#a');
alert(e.is(':disabled'));

var e = $('#b');
alert(e.is(':disabled'));

Which will return false and true.

What's a solution then?

If you want to have an attribute that is actually named disabled use a data-* attribute:

<div id="c" data-disabled="true"></div>

And check it using this JavaScript:

var e = $('#c');
alert(e.data('disabled'));

or:

var e = $('#c');
alert('true' === e.attr('data-disabled'));

Depending on how you're going to handle attached data-*-attributes. Here you can read more about jQuery's .data() which is used in the first example.

Demo:

Try before buy

like image 193
insertusernamehere Avatar answered Oct 11 '22 05:10

insertusernamehere