Reputation: 1399
I have tried rectifying the code below. But I am not able to find a solution. After executing the code, firebug says "document.getElementById(haystack.value) is null". I tried if(document.getElementById(haystack).value ==null)
but it was of no use. Please help me out.
var haystack=document.getElementById('city1').value;
if(!document.getElementById(haystack).value)
{
alert("null");
}
else
{
alert("not null");
}
Edit:
haystack gets the value of the city. When i try an "alert" on haystack -alert(haystack) i get a positive reply. but when i try it with "document.getElementById(haystack).value" i get an error. One thing though, the element with the id that haystack gets might or might not exist.
Edit again:
I think ill kill myself. I put the city for the name attribute for an input element not the id attribute. I am sorry, but sitting in front of the computer this long made me loose my mind. But it is no excuse for having wasted your time. Please accept my sincere apologies. Thanks spender for helping me out.
Upvotes: 1
Views: 286
Reputation: 120390
You're trying to look up a property on document.getElementById('city1')
which might be null. Try this instead:
var haystackElement=document.getElementById('city1');
if(!haystackElement)
{
alert("haystackElement is null");
}
else
{
alert("haystackElement is not null");
var haystack=haystackElement.value;
if(!haystack)
{
alert("haystack is null");
}
else
{
alert("haystack is not null");
}
}
Upvotes: 7
Reputation: 545995
Doing it in less lines:
if ((el = document.getElementById('city1')) && el.value) {
alert ("not null");
} else {
alert ("null");
}
Upvotes: 0
Reputation: 943142
Unfortunately you have shown us some code and described an error (which looks like it has been transcribed incorrectly) without telling us what you are actually trying to achieve.
Take a look at this code sample, it fixes the robustness issues with your code, and has more detailed alert messages to make it clear what is being detected.
Hopefully it will clear things up for you.
var haystack = document.getElementById('city1').value;
var haystack_element = document.getElementById(haystack);
if (haystack_element) {
if (haystack_element.value) {
alert("The element has a true value");
} else {
alert("The element has a false value, such as '' or 0");
} else {
alert("No element with that name");
}
Upvotes: 0
Reputation: 498914
You already have your haystack
object:
var haystack=document.getElementById('city1');
if(!haystack.value)
{
alert("null");
}
else
{
alert("not null");
}
document.getElementById
is used to get the element, you have done that and placed it in the haystack
variable. There is no need to call document.getElementById
again on it (and incorrectly at that). Read about getElementById
.
Upvotes: 0