Ti J
Ti J

Reputation: 271

Hide a table row element inside a table using javascript

I want to hide a table row when a td has no value, but my javascript function is failing. It keeps going on the "else".

HTML

<table>
   <tr id="locOfWorkRow"> 
     <td><span>Location of Work</span></td>
   </tr>
   <tr>
     <td><span>This is the label</span></td>
     <td id="road"><span></span></td>
   </tr>
</table>

Javascript

var r = document.getElementById('road').innerHTML; 

 if(r == ""){ alert("on if");
   document.getElementById('locOfWorkRow').style.display = "none";
 }else{
    alert("on else");
 }

Upvotes: 1

Views: 365

Answers (7)

Sujith
Sujith

Reputation: 206

Instead of innerHTML you may use innerText or textContent

var r = document.getElementById('road').innerText || document.getElementById('road').textContent; 

Upvotes: 0

Keval Bhatt
Keval Bhatt

Reputation: 6322

Actually your if condition is wrong

Example: http://jsfiddle.net/kevalbhatt18/bvop1gdq/

if(r !== ""){ alert("on if");
   document.getElementById('locOfWorkRow').style.display = "none";
 }else{
    alert("on else");
 }

Or

if (r.length > 0) {
    alert("on if");
    document.getElementById('locOfWorkRow').style.display = "none";
} else {
    alert("on else");
}

Upvotes: 0

kwangsa
kwangsa

Reputation: 1711

using undefined as comparison instead of empty string and also use === instead of ==

if(r === undefined){ alert("on if");
  document.getElementById('locOfWorkRow').style.display = "none";
}else{
  alert("on else");
}

Upvotes: 0

Jako Basson
Jako Basson

Reputation: 1531

Instead of checking for an empty string, check whether the length of the innerHTML is more than 0 instead.

r.length > 0

If the string is empty, the length will return 0, if the the innerHTML contains any characters the length will return a value greater than 0.

What you are currently doing with r == "" is checking whether r is empty and that is why the "on if" alert is showing.

See this example

http://jsfiddle.net/9ny6598u/

Upvotes: 2

Vijay Patel
Vijay Patel

Reputation: 173

Hope you are not loading your javascript before page try to write your javascript at the end of the page so the element is available and you not get the null reference.

and by innerhtml you got the "span Road 1 /span" so write condition as per that. and its work fine if you load your script below body.

Make sure you have loaded your script after html load.

Upvotes: 0

Vivek Gupta
Vivek Gupta

Reputation: 1055

You are using wrong if condition

use if(r != "") instead of r==""

Upvotes: 0

Satinder singh
Satinder singh

Reputation: 10198

var r = document.getElementById('road').innerHTML;

if (r.length > 0) {
    alert("on if");
    document.getElementById('locOfWorkRow').style.display = "none";
} else {
    alert("on else");
}

DEMO

Upvotes: 0

Related Questions