s d
s d

Reputation: 203

change table cell background color according to user input using javascript

I am working on a task where based on a user input(numbers from 1 to 9) background color of that particular table cell must change, suppose I enter 2, background color of cell with value 2 must change and previous style should not be retained. any suggestions how it can be done?

Here is what I am trying:

function changeBackground() {
    var x=document.getElementById("coltext").value;
    if (x === '1') {
    document.getElementById(x).style.background = "green";
    }
    if (x === '2') {
    document.getElementById(x).style.background = "green";
    }
    }
<input type="text" id="coltext" name="coltext">
    <button type="submit" onclick="changeBackground()">color me</button>
    <table class="table table-bordered">
    <tr>
    <td id="1">1</td>
    <td id="2">2</td>
    <td id="3">3</td>
    </tr>
    <tr>
    <td id="4">4</td>
    <td id="5">5</td>
    <td id="6">6</td>
    </tr>   
    </table>

Upvotes: 0

Views: 704

Answers (1)

Ahmed Tag Amer
Ahmed Tag Amer

Reputation: 1422

You can do it like this:

( No need to use if conditions or switch cases )

function changeBackground() {
    var x = document.getElementById("coltext").value;
    var tdCount = document.getElementsByTagName("td");
    var i = tdCount.length;
    while (i--) tdCount[i].style.background = "white";
    document.getElementById(x).style.background = "green";
}
table{
  width:100%;
}

table tr td{
  border:1px solid #ddd;
  text-align:center;
  background:white;
}
<input type="text" id="coltext" name="coltext">
    <button type="submit" onclick="changeBackground()">color me</button>
    <table class="table table-bordered">
    <tr>
    <td id="1">1</td>
    <td id="2">2</td>
    <td id="3">3</td>
    </tr>
    <tr>
    <td id="4">4</td>
    <td id="5">5</td>
    <td id="6">6</td>
    </tr>   
    </table>

Upvotes: 1

Related Questions