Reputation: 2430
I want to update the second list based on the item clicked in the first list :
So what I'm doing is that I launch a function on the onclick
property of the links of the first list that does the request and add new elements.
The problem is that every time I click on a different element, the new ones are added to the old ones instead of replacing them, which is normal 'cause I used createElement
.
So I tried to delete the old ones before loading the new ones (commented code) but it did not work :/
function catalogRequest(){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){this.readyState, status, this.responseText};
http.open('GET', 'http://localhost:31000/catalog');
http.send();
http.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
loadCatalog(this.responseText);
}
};
}
function loadCatalog(categoriesText){
let categories = JSON.parse(categoriesText);
console.log(categories);
categories.forEach(element => {
let panel = document.getElementById('catalog');
let panelLink = document.createElement('a');
panelLink.className = 'panel-block';
panelLink.onclick = function(){ categoryRequest(element['id']);};
panelLink.text = element['name'];
panel.appendChild(panelLink);
});
}
function categoryRequest(id){
// Remove the old links before loading the new ones
// let oldLinks = document.getElementsByClassName('category-link');
// console.log(oldLinks);
// for(let item of oldLinks){
// document.removeChild(item);
// }
var http = new XMLHttpRequest();
http.onreadystatechange = function(){this.readyState, status, this.responseText};
http.open('GET', 'http://localhost:32000/list?id=' + id);
http.send();
http.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
loadCategories(this.responseText);
}
};
}
function loadCategories(productsText){
let products = JSON.parse(productsText);
console.log(products);
products.forEach(element => {
let panel = document.getElementById('category');
let panelLink = document.createElement('a');
panelLink.className = 'panel-block category-link';
panelLink.onclick = categoryRequest(element['id']);
panelLink.text = element['name'];
panel.appendChild(panelLink);
});
}
<div class="column">
<nav class="panel is-primary" id="catalog">
<p class="panel-heading">Catalog</p>
</nav>
</div>
<div class="column">
<nav class="panel is-info" id="category">
<p class="panel-heading">Category</p>
</nav>
</div>
Upvotes: 0
Views: 2625
Reputation: 1265
empty categories list before insert:
function loadCategories(productsText){
let products = JSON.parse(productsText);
console.log(products);
let panel = document.getElementById('category');
panel.innerHTML = "";
products.forEach(element => {
let panelLink = document.createElement('a');
panelLink.className = 'panel-block category-link';
panelLink.onclick = categoryRequest(element['id']);
panelLink.text = element['name'];
panel.appendChild(panelLink);
});
}
Upvotes: 2