I'm new to javascript and trying to achieve one thing. I have on my site's table with TD's fetched from API URL by code bellow, with the result as on the image below.
What I'm trying to achieve is to make TD's clickable and an onclick
redirects to another page where fetch URL will change from https://api.ulozenka.cz/v3/consignments to https://api.ulozenka.cz/v3/consignments/id (id from first td array), or at least onlick
redirect to another page and store id from current td first array to variable (PHP variable will be better if it's possible).
Thanks for your reply.
<table id="consignments-list" align="center" style="text-align: center; border-collapse: collapse;
border-spacing: 0;
width: 97%;
border: 3px solid #ddd;" cellpadding="10">
<thead>
<tr>
<th width="20%">ID</th>
<th width="40%">Name</th>
<th width="40%">Status</th>
</tr>
</thead>
<tbody>
<!-- load users here -->
</tbody>
</table>
<script id="jsbin-javascript">
window.onload = () => {
const table = document.querySelector('#consignments-list');
// call API using `fetch`
fetch('https://api.ulozenka.cz/v3/consignments', {
headers: new Headers({
'X-Shop': '18157',
'X-Key': '##################'
})
})
.then(res => res.json())
.then(res => {
// loop over all users
res.data.map(consignment => {
// create a `tr` element
const tr = document.createElement('tr');
// create ID `td`
const idTd = document.createElement('td');
idTd.textContent = consignment.id;
// create Name `td`
const statusTd = document.createElement('td');
statusTd.textContent = `${consignment.status.name}`;
//---
const nameTd = document.createElement('td');
nameTd.textContent = `${consignment.customer_name} ${consignment.customer_surname}`;
// add tds to tr
tr.appendChild(idTd);
tr.appendChild(nameTd);
tr.appendChild(statusTd);
// app tr to table
table.querySelector('tbody').appendChild(tr);
});
})
.catch(err => console.log('Error:', err));
};
</script>