GeForce
GeForce

Reputation: 21

Cannot get user input from text box to change box backgroundColor in Javascript

I am trying to get the user input from the text box to change the background box color for my assignment. I have been playing with this for a while, however, it only works when I set the box value to colorInput.

document.getElementById("box").value;
document.getElementById("box").value;

HTML:

<label for="colorInput">Enter a Color:</label>
        <input id="colorInput" type="text">
        <button id="submitColor" type="button">Submit Color</button>
        <div id="box" class="box"></div>

Javascript:

/** Question 2 */
function submitColor() {
    document.getElementById("submitColor").onclick = function() {
        var inputVal = document.getElementById("box").value;
        if (inputVal.value == "yellow") {
            document.getElementById("box").style.backgroundColor = "yellow";
        } else if(inputVal.value == "red") {
            document.getElementById("box").style.backgroundColor = "red";
        }

    }
}
submitColor();

Upvotes: 0

Views: 57

Answers (2)

GeForce
GeForce

Reputation: 21

var inputVal = document.getElementById("colorInput"); fixed my answer

Upvotes: 0

freefall
freefall

Reputation: 309

A few things going on here:

First - your var inputVal = document.getElementById("box").value; is getting the value of the <div>? I believe that line wants to read var inputVal = document.getElementById("colorInput").value;

Second - your <div> that you are trying to change the background color of currently takes up 0px. You need to either give it a size via CSS or put some content between in the <div></div> tags.

Upvotes: 1

Related Questions