0

I have a situation to check if a LINK made of "a href" is hidden or not. All good.

But we use same javascript in many other pages. So some pages might not have this element (I mean ID). How do I make a null or undefined check so that it doesn't through null error when it evaluates below if condition.

I want to check for this specific ID "AgeCheckbox". The way we usually check for null in C# and then evaluate condition. Please help me.

function Handle(err) {
    if ($('#AgeCheckbox').is(":hidden") == false)
    {
        CalMedicine();
        ShowTotal();
    }   
}

I read some articles, I want it to be strong, using 3 equals or so.

Devnsyde
  • 1,297
  • 1
  • 13
  • 34
Jasmine
  • 5,186
  • 16
  • 62
  • 114
  • `if ( $('#elem_id').length ) {...` – adeneo Feb 18 '16 at 23:12
  • @adeneo: I saw that blog, but I reckon it pretty much doesn't answer my need? – Jasmine Feb 18 '16 at 23:15
  • If you need to check if an element exists or not, it does fit your need pretty much exactly. – adeneo Feb 18 '16 at 23:21
  • `$('#AgeCheckbox').is(":hidden")` will return `false` if the element doesn't exist. A jQuery object will always be returned, it will just be empty. No error should occur there. – Stryner Feb 18 '16 at 23:22
  • Also, you can invert that to `if ( $('#AgeCheckbox').is(':visible') ) {...` which seems to fit better here – adeneo Feb 18 '16 at 23:23
  • @Stryner: Looks good, thank you. – Jasmine Feb 19 '16 at 00:23
  • @adeneo: Maybe. But what if element doesn't exist? As Stryner says it would return false and it won't get into the loop, mate. Right? It will screw up? – Jasmine Feb 19 '16 at 00:24
  • And that's why you could use `:visible` instead, then the condition would only be true if the element exists, and is visible. – adeneo Feb 19 '16 at 00:34

0 Answers0