Matthew Dickens
Matthew Dickens

Reputation: 33

Styling HTML with Javascript based on values

I am trying to style an HTML table row based on values in that row, but I am stuck on step 1 - styling it at all!

Here's the code I have:

<tr id="tablerow<%=j%>">
<script type="text/javascript">
     document.getElementById("tablerow<%=j%>").style.backgroundColor = "red";
</script>

<%=j> is pulling a row number in from the loop that's loading the data from the Access database as it loads the table.

The table rows are not showing up as red!

Then later I am going to use some IF statements in Javascript to color the rows based on data from some of the elements:

var datecheck = new Date;
if (document.getElementById("confirmStatus<%=j%>").value=="P" && (document.getElementById("confirmYear<%=j%>").value < datecheck.getFullYear())) {
        document.getElementById("tablerow<%=j%>").style.backgroundColor = "LightCoral"; }

I was able to figure it out - thanks for the help!

Upvotes: 1

Views: 142

Answers (3)

Malk
Malk

Reputation: 12003

I find it better to use custom attributes instead of string concatenation:

<tr data-dbid="<%=j%>" style="background-color:red">
  <td><input class="confirmYear" /></td>
  <td><input class="confirmStatus" /></td>
</tr>

Then use that when needed:

function checkRow(id) {
    var _tr = document.querySelector("[data-dbid=" + id + "]"),
        _confirmYear = _tr.querySelector(".confirmYear"),
        _confirmStatus = _tr.querySelector(".confirmStatus");

    if (_confirmYear.value === "P" && _confirmStatus.value < datecheck.getFullYear())
       _tr.style.backgroundColor = "LightCoral";

}

window.addEventListener('load',function(){
    [].forEach.call(
       document.querySelectorAll("[data-dbid]"),
       function(el) { checkRow(el.dataset["dbid"]) }
    );
});

Upvotes: 0

Darth
Darth

Reputation: 1650

Your script execute too early - html not ready yet. Try

<tr id="tablerow<%=j%>">
<script type="text/javascript">
     window.addEventListener('load',function(){
         document.getElementByID("tablerow<%=j%>").style.backgroundColor = "red";
     }
</script>

But it's ugly idea do it by js

Upvotes: 0

Mico
Mico

Reputation: 2009

Have you checked your JavaScript console?

Atleast it should be document.getElementById not document.getElementByID

Upvotes: 1

Related Questions