user2573586
user2573586

Reputation: 71

Could you please help me to highlight the selected HTML table row created dynamically through java script

Below is the JavaScript functionalities addRow() I have used to add the rows dynamically and now am trying to highlight the selected row with red color using rowhighlight() function.

/Function to addRows dynamically to the HTML table/

function addRow(msg)
{
    var table = document.getElementById("NotesFinancialSummary");
    var finSumArr1 = msg.split("^");
    var length = finSumArr1.length-1;
    alert("length"+ length);
    for(var i=1; i<finSumArr1.length; i++)
    {

        var rowValues1 = finSumArr1[i].split("|");
        tb=document.createElement("tbody");
        var tbody=document.createElement("tbody");
        table.appendChild(tbody);
        var tr=document.createElement("tr");
        tbody.appendChild(tr);
        for(var k=0;k<=10;k++)//adding data to table dynamically
        {       

            var td=document.createElement("td");
            tr.appendChild(td);
            var element1=rowValues1[k];
            td.innerHTML =element1;
            tr.onclick=function(){

            rowhighlight(this);//calling the rowhighlight function
            }

        }



       }




}


     function rowhighlight(x)
    {

        var index = x.rowIndex;
        document.getElementById("NotesFinancialSummary").rows     [index].style.backgroundColor = "red";



    }

Upvotes: 1

Views: 1259

Answers (1)

Justin Self
Justin Self

Reputation: 6265

One approach is to first loop through the other rows and remove the styling (really should be a class) then apply the styling (again, class) to the selected row.

Here's one way of doing it:

function rowHighlight() {
    var selectedRows = document.getElementsByClassName('selected');

    for (var n = 0; n < selectedRows.length; n++) {
        selectedRows[n].className = '';
    }
    this.className = 'selected'
}

And here's a working example of it, though very simple: fiddle time!

Upvotes: 1

Related Questions