Search code examples
javascripthtml

document.getElementById not working right


When I use the inputs of R: 255, G: 0, B: 255 and press the button, the page should be a magenta color, but nothing happens. Can I do something to fix this? This is my current code for this issue.

<!DOCTYPE html>
<html>
<head>
<title>
Color picker
</title>
</head>
<body style="text-align: center;">
    <h1> COLOR PICKER </h1>
    <label for="R">R: </label>
    <input type="number" maxlength="3" min="0" max="255" id="r">
    <label for="G">G: </label>
    <input type="number" maxlength="3" min="0" max="255" id="g">
    <label for="B">B: </label>
    <input type="number" maxlength="3" min="0" max="255" id="b"><br><br>
    <input type="submit" onclick="getColor()">Get color</input>
    <script>
    function getColor() {
        var r = document.getElementById("r");
        var g = document.getElementById("g");
        var b = document.getElementById("b"); 
        var color = "rgb("+ [r,g,b].join(',')")";
        document.body.style.background = color;
    }
    </script>
</body>

</html>


Solution

  • You need to get the .value of each input element.

        var r = document.getElementById("r").value;
        var g = document.getElementById("g").value;
        var b = document.getElementById("b").value;
    

    and you are also missing a + on your string concatenation

    var color = "rgb(" + [r,g,b].join(',') + ")";