0

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>

1 Answer 1

1

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>

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

1 Comment

@shrutid you are welcome, if this solution answers your question, please click on the check mark on the left side of the answer, thank you.

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.