this is my xml file :-
<root>
<child1 entity_id = "1" value= "Asia">
<child2 entity_id = "2" value = "india">
<child3 entity_id = "3" value = "Gujarat">
<child5 entity_id = "5" value ="Rajkot"></child5>
</child3>
<child4 entity_id = "4" value = "Rajshthan">
<child6 entity_id = "6" value = "Ajmer"></child6>
</child4>
</child2>
</child1>
</root>
this is my code :-
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script>
data = false;
loaded = false;
function loadChild(id) {
if(!loaded) {
ul = "<ul>";
$(data).find("[entity_id='" + id + "']").children().each(function(){
var value_text = $(this).attr('value');
var id = $(this).attr('entity_id');
ul += "<li id='" + id + "'>" + value_text + "</li>";
});
ul += "</ul>";
$("#" + id).append(ul);
loaded = true;
}
}
$(function() {
$('#update-target a').click(function() {
$.ajax({
type: "GET",
url: "final.xml",
dataType: "xml",
success: function(xml) {
data = xml;
//console.log(data);
$(xml).find('child1').each(function(){
var value_text = $(this).attr('value');
var id = $(this).attr('entity_id');
$("<li id='" + id + "' onclick=\"loadChild('" + id + "');\"></li>")
.html(value_text)
.appendTo('#update-target ol');
}); //close each(
}
}); //close $.ajax(
}); //close click(
}); //close $(
</script>
</head>
<body>
<p>
<div id='update-target'>
<a href="#">Click here to load value</a>
<ol></ol>
</div>
</p>
</body>
</html>
i got the output something like this :-
Asia
India
i want something like this output:-
if click on Asia then display India
if click on India then display Gujarat and Rajshthan
if click on Gujarat then display Rajkot
if click on Rajshthan then display Ajemr
Firstly, if you want to continually click on the child values, you will need to add your loadChild function as a click event on each child list item. So, instead of this line
You need this line
However, this leads on to the next issue. You are using a global variable loaded to check whether the XML has already been read. But once this has been set to true (when clicking india) then the loadChild function will not do anything else. You really need to keep a track of the loaded value for each separate child. You could make use of the jquery data function here, for example
Note that another thing you will need to avoid is that when clicking on a child element, you want to avoid the onclick event of the parent firing (which may happen because the child element is embedded within the parent’s li) element, and so you will need to tell the browser not to bubble up the click event.
Finally, to simplify the code a bit, you could actually get the click handler for update-target a to call your loadChild function, but using a ‘dummy’ element with an id of 0.
Try the following code instead: