Check div is hidden using jQuery
Asked Answered
B

6

37

This is my div

<div id="car2" style="display:none;"></div>

Then I have a Show button that will show the div when you click:

$("show").click(function() {
    $("$car2").show();
}); 

So right now I want to check if the div #car2 is still hidden before form submission:

if($('#car2').is(':hidden')) {
    alert('car 2 is hidden');
}

Now here is the problem. Although the div #car2 already show, I still got alert message which means that jQuery assumes the div #car2 is still hidden.

My jQuery version is 1.7.

Thanks.

EDIT:

As jasper said, my code is correct and can be run via this demo.

What I suspect there is some conflict with jQuery form to wizard plugin that I am using with my form. Anyone have any idea to solve this?

Burden answered 13/12, 2011 at 4:16 Comment(2)
jsfiddle.net/YjP4K/2 Your code does work when simplified so maybe you have an error somewhere else?Fortunate
See also Checking if an element is hidden [by jquery]Seizure
F
69

You can check the CSS display property:

if ($('#car').css('display') == 'none') {
    alert('Car 2 is hidden');
}

Here is a demo: http://jsfiddle.net/YjP4K/

Fortunate answered 13/12, 2011 at 4:21 Comment(4)
although other answer is correct, but somehow i can only use this method in my form so i will choose this as an answer. thanks.Burden
$('#car').is(:hidden) should work. This also is a cleaner solution than the current one. Check more at api.jquery.com/hidden-selectorEjecta
@Ejecta yeah that makes more semantic sense. I think there are edge cases where doing your own check makes sense because there are conditions around the element(s) that screw with the :hidden and :visible selectors.Fortunate
@Ejecta you forgot the quotes on :hidden. It should be $('#car').is(':hidden')Radley
K
31

Try:

if(!$('#car2').is(':visible'))
{  
    alert('car 2 is hidden');       
}
Knickknack answered 13/12, 2011 at 4:22 Comment(0)
C
11

Try

if($('#car2').is(':hidden'))
{  
    alert('car 2 is hidden');       
}
Chamberlin answered 20/2, 2015 at 8:1 Comment(0)
D
4

Try checking for the :visible property instead.

if($('#car2').not(':visible'))
{
    alert('car 2 is hidden');       
}
Destructionist answered 13/12, 2011 at 4:22 Comment(0)
S
2

Did you notice your typo, $car2 instead of #car2 ?

Anyway, :hidden seems to be working as expected, try it here.

Saying answered 13/12, 2011 at 4:41 Comment(0)
D
1

You can use,

if (!$("#car-2").is(':visible'))
{
      alert('car 2 is hidden');
}
Dolliedolloff answered 5/7, 2016 at 8:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.