Home > OS >  How can I use the <input> method, the <onclick = "func()">, and javascript to
How can I use the <input> method, the <onclick = "func()">, and javascript to

Time:12-25

This is my current code for this issue. Is there anything that I can put inside the script tag

<!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>

For instance with input: R: 255, G: 0, B: 255 and when I want the page should be a lovely magenta color. But when I actually press the button nothing happens. Can I do something to fix this

CodePudding user response:

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(',')   ")";
  •  Tags:  
  • html
  • Related