36

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?

Syscall
  • 16,959
  • 9
  • 22
  • 41
cyberfly
  • 5,088
  • 8
  • 41
  • 61
  • 1
    http://jsfiddle.net/YjP4K/2/ Your code does work when simplified so maybe you have an error somewhere else? – Jasper Dec 13 '11 at 04:26
  • See also [Checking if an element is hidden \[by jquery\]](https://stackoverflow.com/questions/178325/checking-if-an-element-is-hidden) – Adam Katz Oct 03 '15 at 01:59

6 Answers6

68

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/

Jasper
  • 74,169
  • 13
  • 144
  • 142
  • 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. – cyberfly Dec 13 '11 at 06:07
  • 1
    `$('#car').is(:hidden)` should work. This also is a cleaner solution than the current one. Check more at https://api.jquery.com/hidden-selector/ – akshay Apr 10 '15 at 11:52
  • 1
    @akshay 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. – Jasper Apr 12 '15 at 07:51
  • @akshay you forgot the quotes on :hidden. It should be $('#car').is(':hidden') – Ankush Raghuvanshi Jul 21 '16 at 21:17
30

Try:

if(!$('#car2').is(':visible'))
{  
    alert('car 2 is hidden');       
}
Omtara
  • 2,637
  • 1
  • 16
  • 31
10

Try

if($('#car2').is(':hidden'))
{  
    alert('car 2 is hidden');       
}
Sadikhasan
  • 17,212
  • 19
  • 72
  • 111
4

Try checking for the :visible property instead.

if($('#car2').not(':visible'))
{
    alert('car 2 is hidden');       
}
Phil.Wheeler
  • 16,458
  • 9
  • 95
  • 151
2

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

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

Jenz
  • 8,009
  • 6
  • 38
  • 69
smendola
  • 2,005
  • 1
  • 12
  • 14
1

You can use,

if (!$("#car-2").is(':visible'))
{
      alert('car 2 is hidden');
}
SharK
  • 1,899
  • 1
  • 17
  • 26