afash ahamed afash ahamed - 4 years ago 233
Javascript Question

How to hide li tags, if the id is not in JSON using jQuery?

I have a fixed menu with li tags. I want to display only the li tags whose id is present in JSON. If the id is not in JSON the li tag will be not displayed.

This is my HTML:

<ul>
<li id="1"><a href="#">Screen 1</a></li>
<li id="2"><a href="#">Screen 2</a>
<ul>
<li id="3"><a href="#">Screen 3</a></li>
<li id="4"><a href="#">Screen 4</a></li>
</ul>
</li>
<li id="5"><a href="#">Screen 5</a></li>
<li id="6"><a href="#">Screen 6</a></li>
<li id="7"><a href="#">Screen 7</a></li>
<li id="8"><a href="#">Screen 8</a></li>
</ul>


This is my CSS:

#1,#2,#3,#4,#5,#6,#7,#8{
display:none;
}


This is my JSON:

[
{ "ScreenID": 2,
"ScreenName": "Screen 2"
},
{
"ScreenID": 3,
"ScreenName": "Screen 3"
},
{
"ScreenID": 5,
"ScreenName": "Screen 5"
}
]


Now, only li tag with id 2, 3, and 5 should be visible.

Answer Source

Try this:

$.each(jsonArray, function(index, value) {
  var id = jsonArray[index].ScreenID;
  $('#' + id).show();
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download