Using Intraweb.
I create a table on runtime, in modal, has ID, Table has ID and every td has unique ID.
I get a return van the Ajaxcall, but not the ID from the td which was selected.
With a table in the mainscreen (lower script) it works fine.
<div class="modal show" id="View" style="text-align: center; display: block;" aria-modal="true">
<div class="modal-dialog">
<div class="modal-content BG">
<div class="modal-header center CH"><b>List</b></div>
<div class="modal-body">
<span class="LDATACSS" id="LDATA" style="" title="">
<table id="ViewTable" class="fs" style="width:100%">
<tbody>
<tr id="1">
<td id="VW1">Cell 1</td>
</tr>
<tr id="2">
<td id="VW2">Cell 2</td>
</tr>
</tbody>
</table>
</span>
</div>
</div>
</div>
</div>
<script>
<!-- used by table in modal "View" and I cannot find the ID of the clicked <td> -->
$('#View').on('click', function () {
var vc=$(this).closest("td")
ajaxCall("IH", "Params=" + "VW"+vc.attr('ID'))
});
<!-- used by table in main screen, this works fine-->
$('table td').click(function () {
var c = $(this).closest("td")
if (Number(c.attr('ID')) > 0) { c.addClass("Select") }
ajaxCall("IH", "Params=" + c.attr('ID'))
});
</script>
I need the syntax how to retrieve the ID of the <td>
and send it with the Ajaxcall
In this click handler:
$('#View').on('click', function () {
var vc = $(this).closest("td")
ajaxCall("IH", "Params=" + "VW"+vc.attr('ID'))
});
The reference to this
refers to the element handling the click, which in this case is the #View
element. It doesn’t have a “closest <td>
” so nothing matches that and the resulting call to .attr('ID')
returns undefined
.
You can keep the click handler on the #View
element, but also use event delegation (adding a second selector to .on()
) to target clicks from those <td>
elements. That would make the <td>
itself the reference for this
(in which case you don’t even need to use closest()
.
For example:
$('#View').on('click', 'td', function () {
// ^--- using event delegation
var vc = $(this); // <--- remove the call to closest()
console.log("Params=" + "VW"+vc.attr('ID'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="modal show" id="View" style="text-align: center; display: block;" aria-modal="true">
<div class="modal-dialog">
<div class="modal-content BG">
<div class="modal-header center CH"><b>List</b></div>
<div class="modal-body">
<span class="LDATACSS" id="LDATA" style="" title="">
<table id="ViewTable" class="fs" style="width:100%">
<tbody>
<tr id="1">
<td id="VW1">Cell 1</td>
</tr>
<tr id="2">
<td id="VW2">Cell 2</td>
</tr>
</tbody>
</table>
</span>
</div>
</div>
</div>
</div>
2