1

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 ?

6
  • jquery will hlep, is it allowed ? Commented Jul 27, 2015 at 12:44
  • Yes, do you use jQuery? Commented Jul 27, 2015 at 12:47
  • Actually I'm not much familiar with jquery. Can't it be done in javascript ? Commented Jul 27, 2015 at 12:51
  • 1
    Why you are using two nested loops? You don't need second one - you can remove all "if"s and whole for cycle Commented Jul 27, 2015 at 12:52
  • @areim yes we can remove it. Commented Jul 27, 2015 at 12:53

6 Answers 6

3

Here you go! Add a function to your button onclick while creating it and write a function as below:

DEMO

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:

DEMO

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:

DEMO

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:

DEMO

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.

}
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks @GuruprasadRao your code is working but in this way if I click another row select button then that row is also being highlighted. If we can erase the previous row colour and highlight the new one then that would be very helpful.
@AnuragChakraborty updated answer.. check and let me know!!
I don't know but with CSS it's not working. Earlier code was working fine. It's not giving any error in console. Simply not working
did you check the demo??
yeah in try it editor (w3schools) also it's working fine. can we do it without css class ?
|
3

You can achieve what you want by adding an onclick function to your button:

<button type='button' onclick='highlight(this)'>

And then include the function before your loop:

function highlight(button) {
    button.parentNode.parentNode.className = 'highlight';
    // the first parentNode is the td
    // the second is the tr, 
    // then you add a class of highlight to the row
}

And add the css for the highlight:

.highlight {background:red;}

Example fiddle

6 Comments

Could be a user called simi tkd - downvotes seemed to happen as his answer was deleted
Any ways to visit his profile!! Even he might have got reputation down!
from my side too +1 !! We have valid answers!!
Your code works perfectly. But how can we revert/toggle it? Like if we click again select button of another row previous coloured row will be gone and this new row will be highlighted. Do you have any idea ?
you need to check to see if the classname is already added: jsfiddle.net/mskwbo93/3
|
1

Have a look at following snippet:

function hightLight(ele)
{
    ele.parentElement.parentElement.className = "highlight";
}

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 onclick='hightLight(this)' type='button'>select</button></td>");
    }
       document.write("</tr>");
  }
       document.write("</table>");
.highlight
{
  background-color:yellow;
  }
<!DOCTYPE html>
<html>
<body>
</body>
</html>

Comments

1

I would advise against using a button here and rather use the checkboxes which you already have. If you use a button to select a row, then how would you de-select it? You can then use the buttons to fire up actions on the selected row.

From a raw Javascript perspective (i.e. without using any library like jQuery etc.), you can work your algorithm like this:

  1. Find all checkboxes in the table,
  2. Bind a "change" event to all these checkboxes,
  3. If the checkbox is checked then select the row by changing its parent's (td) parent (tr) background color.

Putting this together:

var chk = document.querySelectorAll("table input[type=checkbox]");

for (i = 0; i < chk.length; i++) {
    chk[i].addEventListener("change", function() {
        selectRow(this);
    });
}
function selectRow(elem) {
    if (elem.checked) {
        elem.parentNode.parentNode.style.backgroundColor = 'yellow';
    } else {
        elem.parentNode.parentNode.style.backgroundColor = '';
    }
}
<table>
    <thead>
        <tr><th>Select</th><th>Name</th><th>Location</th></tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" /></td>
            <td>Name 1</td>
            <td>Location 1</td>
        </tr>
        <tr>
            <td><input type="checkbox" /></td>
            <td>Name 2</td>
            <td>Location 2</td>
        </tr>
        <tr>
            <td><input type="checkbox" /></td>
            <td>Name 3</td>
            <td>Location 3</td>
        </tr>
    </tbody>
</table>

Comments

0

Try like this if you caan use JQuery Demo

$("button").on("click", function () {
    $("tr").each(function () {
        $(this).removeClass("highlight");
    });
    $(this).closest("tr").addClass("highlight");
});

CSS:

.highlight {
    background-color:#ccc;
    color:#000000;
    font-weight:bold;
}

Comments

0
$('#your_table_id').on('click', 'td', function () {
  $(this).closest('tr').css({'background-color': 'red'});
});

3 Comments

Please add some explanation to your answer.
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.
i agree this is not pure javascript . JQuery comment: I register function after your code. If somebody clicks on td, function searches parent 'tr' element and highlights it to red

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.