0

I can't get the the conditional to work in this function, any help?

function headupdate(id, name, heading)
{
    var order;
    if (document.getElementById(heading).value === undefined)
    {
        order = 1;
    }
    else
    {
        order = document.getElementById(heading).value;
    }
    alert(order);
    $.post('headingupdate.php', {id: id, name: name, value: heading, order: order},
        function(response)
        {
            $('#resume').html(response)
        }
    )
};
kevinji
  • 10,259
  • 4
  • 36
  • 56
Clay Smith
  • 189
  • 1
  • 4
  • 14

2 Answers2

1

You should check as following.

var head = document.getElementById(heading);
if(head!=null)
{
  order = head.value;
}
else
{
order=1;
}
PSK
  • 16,571
  • 4
  • 31
  • 42
0

In response to your post title, I use typeof() to find if an element exists in the DOM:

if(typeof(document.getElementById('someElement')=='undefined')) {
  alert('Element DNE');
}

Also, typeof() returns a string, so it needs to be in quotes for a conditional statement

"undefined"
Ben
  • 51,262
  • 47
  • 169
  • 217
  • nope, not working. I reversed it, typeof(document.getElementById('someElement').value=='string' is fine. however is the object i'm looking for is not on the page i get an error in the javascript. any other ideas? – Clay Smith Jun 10 '11 at 04:35
  • `getElementById()` returns `null` if the element doesn't exist, and `typeof null` returns `"object"`, so I don't see how `typeof ... == "undefined"` works for you (it didn't work for me when I tried it). – nnnnnn Jun 10 '11 at 06:44