Requirement is to get the value of the id on click on any of the table row data.
Please find the fiddle : http://jsfiddle.net/T887t/55/
Below is the javascript i tried:
<script>
function test(){
alert("test called");
var serviceID = $(this).attr('id');
alert("serviceID :: " + serviceID);
}
</script>
html code:
<table border="1">
<tr>
<th><b> Column1 </b> </th>
<th><b> Column2 </b> </th>
</tr>
<tr>
<td class="navigateTest" id="88" onclick="test()"> Row1 - Data1 </td>
<td class="navigateTest" id="98" onclick="test()"> Row1 - Data2 </td>
</tr>
<tr>
<td class="navigateTest" id="33" onclick="test()"> Row2 - Data1 </td>
<td class="navigateTest" id="55" onclick="test()"> Row2 - Data2 </td>
</tr>
</table>
Could not able to get the value of the id in javascript function. The value of the id is dynamic on my application. Please suggest.
If you are going to use jQuery, then use its event binding as well
$('.navigateTest').click(function(){
alert("test called");
var serviceID = this.id;
alert("serviceID :: " + serviceID);
});
You will no longer need to inline onclick=test() with this snippet.
This will query for all of the elements with class=nagivateTest and assign a click handler to them. Once clicked, this will refer to the element clicked inside of the callback.
The reason your original code does not work is because this in the global callback is window and will not relate to the current element clicked.
If you are going to include this code in the head or in a linked file, make sure to wrap the code in the ready callback so that the DOM has been parsed and the .navigateTest elements are available. That would look like this:
$(function(){ //jQuery shortcut for .ready (ensures DOM ready)
$('.navigateTest').click(function(){
alert("test called");
var serviceID = this.id;
alert("serviceID :: " + serviceID);
});
});
Here is a working jsFiddle.
Using plain javascript you can use event listeners to run only when the table is clicked. Using event listeners avoids the need to inline javascript Which is considered bad practice (when it can be avoided) and results in cleaner and easier to maintain / read code. Read this for more information on event listener.
<script>
// get a reference to the table
var table = document.querySelector('table');
// listen for a click
table.addEventListener('click', function(ev){
// get the event targets ID
var serviceID = ev.target.id;
alert(serviceID);
})
</script>
<table border="1">
<tr>
<th><b> Column1 </b> </th>
<th><b> Column2 </b> </th>
</tr>
<tr>
<td class="navigateTest" id="88"> Row1 - Data1 </td>
<td class="navigateTest" id="98"> Row1 - Data2 </td>
</tr>
<tr>
<td class="navigateTest" id="33"> Row2 - Data1 </td>
<td class="navigateTest" id="55"> Row2 - Data2 </td>
</tr>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With