lolio lolio - 1 month ago 5
Javascript Question

Giving <td>-Elements an ID with JSP

I'am new to Javascript/Jquery and JSP.
I have a

<table>
created with JSP ( 2 for-loops ), and with Javascript I can click on every Cell.This opens a new Window (Window is opened by Bootstrap Script) with an Text Input and an DELETE and SAVE-BUTTON.

<thead>
<tr>
<%for(int i = 0; i <bsp.length;i++) { %>
<%if(i==0){ %>
<th></th>
<%} %>
<th><%out.println(bsp[i]); %></th>
<%} %>
</tr>
</thead>
<tbody>
<%for(int ut = 0; u < test.length ;u++) { %>
<tr>
<td><%out.println(test[u]); %></td>
<%for(int rest =0; rest<bsp.length;rest++) { %>
<td id="ID00" class="td_test"></td>
<%} %>
</tr>
<%} %>
</tbody>


$(document).ready(function() {
$("#save").click(function() {
$(".td_test").append($("#input").val());
});
});


The Problem is, that every
<td>
-Element has the same Class, and if I change one Cell, it changes the whole Table.If i use ID-Selektor, it only works with the very first Cell in Table.

Anyone has some ideas how I can solve that individually?

Answer

As discussed in the comments, grab the originating element inside its click handler:

$(document).ready(function() {
    var currentlyOpenedTd; // name it something more sensible
    $(".td_test").click(function() {
         $("#bModal").modal('show');
         currentlyOpenedTd = this;
    });
    $("#save").click(function() {
         $(currentlyOpenedTd).text($("#input").val());
    });
});

An aside: also notice that I changed .append to .text, even though they're not exactly the same. Modify to suit your requirements, but keep in mind it's good practice to always sanitize user input.