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?

Syscall
  • 19,327
  • 10
  • 37
  • 52
cyberfly
  • 5,568
  • 8
  • 50
  • 67
  • 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

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/

Jasper
  • 75,717
  • 14
  • 151
  • 146
  • 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
  • 2
    `$('#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,911
  • 2
  • 19
  • 31
11

Try

if($('#car2').is(':hidden'))
{  
    alert('car 2 is hidden');       
}
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
4

Try checking for the :visible property instead.

if($('#car2').not(':visible'))
{
    alert('car 2 is hidden');       
}
Phil.Wheeler
  • 16,748
  • 10
  • 99
  • 155
2

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

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

Jenz
  • 8,280
  • 7
  • 44
  • 77
smendola
  • 2,273
  • 1
  • 15
  • 14
1

You can use,

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