I am using below code to generate a dynamic table-
<!DOCTYPE html>
<html>
<head>
<script>
document.write("<table id=appTable border=1 style=margin-top:10px; margin-left:10px;>");
document.write("<tr><th>Select</th><th>Name</th><th>Location</th><th>Action</th></tr>");
for (row = 1; row < 5; row++) {
document.write("<tr>");
for (col = 1; col <= 4; col++) {
if(col == 1) {
document.write("<td><input type='checkbox' id='mapCheck' name='myTextEditBox' /></td>");
}
if(col == 2) {
document.write("<td width='140'>Name</td>");
}
if(col == 3) {
document.write("<td width='200'>Location</td>");
}
if(col == 4) {
document.write("<td><button type='button'>select</button></td>");
}
}
document.write("</tr>")
}
document.write("</table>")
</script>
</body>
</html>
When the select button is clicked the table row should highlight the entire row. Any idea how to implement it in javascript
& css
?
Here you go! Add a function to your button onclick
while creating it and write a function as below:
So changed button html before appending will be
document.write("<td><button type='button' onclick='highlight(this)'>select</button></td>")
^^^^^Add this
and a function
function highlight(ctrl){
var parent=ctrl.parentNode.parentNode;
parent.style.background='red';
}
UPDATE
To remove previous selected on click of other below is one of the approach you can opt to:
CSS
.backChange{
background:red;
}
JS
Scenario 1
function highlight(ctrl){
var elements=document.getElementsByTagName('tr'); //get all the tr elements
for(var i=0;i<elements.length;i++)
elements[i].className=''; //clear the className from all the tr elements
var parent=ctrl.parentNode.parentNode;
parent.className="backChange"; //add ClassName to only this element's parent tr
}
Scenario 2
Now If you have classList
that are already there in tr
and you just want to add or remove one particular class
which changes its style
then you can do it as below:
function highlight(ctrl){
var elements=document.getElementsByTagName('tr');
for(var i=0;i<elements.length;i++)
elements[i].classList.remove('backChange'); //remove one particular class from list of classNames in that element
var parent=ctrl.parentNode.parentNode;
parent.classList.add("backChange");//Add that particular class to classList of element's parent tr
}
UPDATE 2
Without using Class and applying inline styles
you can try as below:
function highlight(ctrl){
var elements=document.getElementsByTagName('tr');
for(var i=0;i<elements.length;i++)
elements[i].style.background=''; //remove background color
var parent=ctrl.parentNode.parentNode;
parent.style.background="red";//add it to specific element.
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments