Adding an onclick event to a table row
Something like this.
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
EDIT
Working demo.
How to add a onclick event to a table cell using javascript?
onclick
is a html property, you have assign a function to this property to handler click event.
In you case:
cell1.onclick = xfunc; // instead of cell1.onclick()="xfunc()";
Add onclick event to each row in a table
You are assigning a new value to innerHTML
.
This erases all the existing DOM elements and the event handlers attached to them and creates new ones (but you haven't got any code to recreate the event handlers you are deleting).
Don't use innerHTML
. Use standard DOM methods: createElement
, appendChild
, etc. Then you can add your new row to the table body without changing what is already there.
How to generate a new table row with an onClick event
Very easy. You can use insertAdjacentHTML
function addNewRow() { let tds = document.getElementsByTagName("td"); tds[tds.length - 2].insertAdjacentHTML('afterend', '<td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td>')}
<table class="table table-bordered"> <thead> <tr> <th>Description</th> <th>Image</th> </tr> </thead> <tbody> <tr> <td><textarea rows="5" cols="1" placeholder="Enter task description here..."></textarea></td> <td><input type="file" onchange="previewFile()"><img src="" height="80"></td><br> </tr> </tbody></table><input type="button" value="Add new row" onclick="addNewRow()">
How to add click event to table cell in this code?
Add this code:
cell.addEventListener("click",function(){
alert("cell clicked");
});
After this code:
cell = row.insertCell(j);
It will add event listener to each cell. when clicked it will show an alert.
JavaScript to add table row onclick events
This seem to be the canonical way
DEMO
function example4() {
var table = document.getElementById("tableid4");
var rows = table.rows; // or table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
rows[i].onclick = (function() { // closure
var cnt = i; // save the counter to use in the function
return function() {
alert("row"+cnt+" data="+this.cells[0].innerHTML);
}
})(i);
}
}
window.onload = function() { example4(); }
UPDATE: @ParkerSuperstar suggested that the i in (i) is not needed.
I have not tested this but his fiddle seems to work.
How would I add an onclick event for a table row. ex: if the decline button is pressed, that rows background turns red
Here you go with the solution https://jsfiddle.net/qwyjkcrr/
var people = [];var data = { "person": [ { "firstName": " ", "lastName": "Kent", "job": "Reporter", "roll": 20, "hours":10 }, { "firstName": " ", "lastName": "Wayne", "job": "Playboy", "roll": 30, "hours":20 }, { "firstName": " ", "lastName": "Scott", "job": "PaperMan", "roll": 20, "hours": 40 } ]};
var row = 0;
$.each(data.person, function(i, f) { var tblRow = "<tr>" + "<td><button class='button-border toggleModal toggleModalFromTable'><span class='icon'></span> Timesheet Approval</button></td>" + "<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "<td>" + f.hours + "</td>" + " </tr>" $(tblRow).appendTo("#userdata tbody"); $('#userdata').on('click', '.toggleModalFromTable', function (e) { row = $(this).closest('tr').index() + 1; $('.modal').toggleClass('active'); });});
$('.approve').click(function(){ $('.modal').toggleClass('active'); $('table tbody tr:nth-child(' + row + ')').remove();});
$('.disapprove').click(function(){ $('.modal').toggleClass('active'); $('table tbody tr:nth-child(' + row + ')').css({ 'background': 'red' });});
html{ font:0.75em/1.5 sans-serif; color:#333; background-color:#fff; padding:1em; }
/* Tables */table{ width:100%; margin-bottom:1em; border-collapse: collapse; border: 1px; }th{ font-weight:bold; background-color:#ddd; } td{ padding:0.5em; border:1px solid black; } tr:nth-child(even) { background-color: #ddd; } a.button { -webkit-appearance: button; -moz-appearance: button; appearance: button;
text-decoration: none; color: initial;}
@font-face { font-family: 'ios7-icon'; src: url("//ios7-icon-font-demo.herokuapp.com/fonts/ios7-icon.woff") format("woff"), url("//ios7-icon-font-demo.herokuapp.com/fonts/ios7-icon.ttf") format("ttf"); font-weight: normal; font-style: normal;}*, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;}
body { padding: 50px; font-family: 'Helvetica Neue' !important; font-weight: 300;}
.wrapper { max-width: 500px; margin: 0 auto;}
h1 { font-weight: 100; font-size: 45px; color: #007aff;}
h2 { font-weight: 500; font-size: 21px; margin-bottom: 15px;}
section { margin-top: 30px;}section p { line-height: 1.4; margin-bottom: 20px;}
button { -webkit-appearance: none; -moz-appearance: none; -ms-appearance: none; -o-appearance: none; appearance: none; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; border: none; outline: none; font: inherit; cursor: pointer; margin: 0; padding: 0; background: LightBlue; color: #007aff; font-weight: 300; font-size: 14px; -moz-border-radius: 0px; -webkit-border-radius: 0px; border-radius: 0px; /* &:nth-child(even){ */ /* background: white; */ /* } */ /* &:last-child { border-color: red; margin-bottom: 0; }*/}button:hover { text-decoration: underline;}button.button-border { -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; padding: 10px 12px 8px 12px; border: 1px solid #007aff;} button.button-border:hover { background: #007aff; color: #ffffff; text-decoration: none; } button.button-success { /color: #4dd865; */ border-color: #4dd865; } button.button-success:hover { background: #4dd865; } button.button-error { color: #ff3b30; border-color: #ff3b30; } button.button-error:hover { background: #ff3b30; }
.modal { display: none; position: fixed; top: 50%; left: 50%; width: 430px; height: auto; margin-left: -200px; margin-top: -150px; background-color: #ffffff; padding: 25px; border-radius: 5px; z-index: 10; box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5);}.modal.active { display: block;}.modal header { position: relative;}.modal h2 { text-align: center;}.modal .close { position: absolute; top: 3px; right: 0; margin: 0;}
.pull-right { float: right;}
.icon { display: inline-block; font-size: inherit; font-family: circle; margin-right: 5px; color: inherit; -webkit-text-rendering: geometricPrecision; -moz-text-rendering: geometricPrecision; -ms-text-rendering: geometricPrecision; -o-text-rendering: geometricPrecision; text-rendering: geometricPrecision;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table id="userdata" rules="groups" style="border: 1px solid black;"> <thead>
<tr> <th> </th> <th>EmployeeNum</th> <th>EmployeeName</th> <th>ChargeNum</th> <th>Hours</th> </tr>
</thead>
<tbody>
</tbody></table>
<div class="modal">
<header> <button class="close toggleModal">Close</button> </header>
<section> <p>To approve the timesheet and submit it to WAM press "Approve", to decline the timesheet for later viewing press "Disapprove"</p> </section>
<button class="button-border button-success toggleModal approve"> <span class="icon"></span> Approve </button>
<button class="button-border button-error pull-right toggleModal disapprove"> <span class="icon"> < </span> Disapprove </button> <!-- <script> $(docuemnt).ready(function(){ --> <!-- var rowCount = $('table#tableId tr:#a').index() + 1; --> <!-- $("#a").style.color = "red"}); --> <!-- </script> -->
</div>
Related Topics
Pure JavaScript Method to Wrap Content in a Div
Changing the Selected Option of an HTML Select Element
Very Simple, Very Smooth, JavaScript Marquee
How to Get the Position of Text Within an Element
How to Get Query String Value from Script Path
How to Add CSS With JavaScript
Does .Css() Automatically Add Vendor Prefixes
Execjs::Runtimeerror on Windows Trying to Follow Rubytutorial
How to Select Multiple Files With ≪Input Type="File"≫
How to Replace Text Inside a Div Element
Dynamically Creating HTML Elements Using JavaScript
Fetch(), How to Make a Non-Cached Request
Add Content to a New Open Window
Why the Onclick Element Will Trigger Twice For Label Element
How to Do Fade-In and Fade-Out With JavaScript and Css
Scrollable Div to Stick to Bottom, When Outer Div Changes in Size