Reputation: 3250
I have a rest call in my application (spring based) to update the User's Active (boolean) status using Fetch API like below:
async function activateUser(obj) {
var fullURL = obj.getAttribute("href");
let response = await fetch(fullURL, {
method: 'POST'
});
let result = await response.json();
if (response.ok) {
alert(result.username + " Activated Successfully.. !!");
obj.parentElement.parentElement.cells[6].innerHTML = "true";
//getAllUsersApi(endpoint);
} else {
alert(response.status + "Error Occurred.. !!");
}
}
All works well.
Now, I am trying to update just that cell of my html table to true
whose Initial value was false
. I am updating the html table's cell by hard-coding the column number using (as you can see above too) - obj.parentElement.parentElement.cells[6].innerHTML = "true";
. I was wondering if there is some way we can find the false
in that row for that particular user and update that cell only. Prior to this I was reloading the entire table (the commented line in the JS code above), which nobody will prefer. I tried to find the solution here and here. But couldn't find the stating point for my situation.
From my rest call I am returning the User object so I was just wondering if I could search the table (on client side) just for that particular user and update that just one corresponding cell. In the table Id, Username and email are unique if that helps to find and replace false to true..
Summarized question: How can I update just one cell of my html table by utilizing the response from my REST call?
Upvotes: 0
Views: 1095
Reputation: 349956
There is not really much magic to do. Instead of targetting cell 6, you would check find out the column number by finding the column header that has the title "Enabled". Replace this:
obj.parentElement.parentElement.cells[6].innerHTML = "true";
With:
let row = obj.closest("tr");
let titles = row.closest("table").querySelectorAll("th");
for (let cellNo = 0; cellNo < titles.length; cellNo++) {
if (titles[cellNo].textContent.includes("Enabled")) {
row.cells[cellNo].textContent = "true";
}
}
This is based on the information you have given in the question (not behind links) and in comments/chat.
Upvotes: 1
Reputation: 223
Since each ID is unique, you can add that to each row as an id="user id goes here"
attribute. Then each cell can be given a class to specify it's purpose.
For example:
<table>
<tr id="user_{{ user ID }}">
<td class="user-name">{{ user name }}</td>
<td class="user-email">{{ user email address }}</td>
<td class="is-user-active">{{ user active status }}</td>
</tr>
</table>
Since the result is returning the username, I am guessing it can also return the ID, in which case your code would look like this:
if (response.ok) {
let isUserActive = document.querySelector(`#user_${result.id} .is-user-active`);
isUserActive.innerHTML = "true"
}
Upvotes: 1