Search code examples
javascripthtmlradio-button

Change background color using radio buttons


I am creating a form that uses radio buttons for one of my questions.

I wish for the radio buttons to change the background colour (each holding a different value)
eg. button 1 changes to red while 2. changes it to blue.

JavaScript

function changeColour() {
    if("r")
        document.body.style.backgroundColour="#FF0000";
    if("b")
        document.body.style.backgroundColour="#0000FF";
    if("p")
        document.body.style.backgroundColour="#FF00FF";
}

HTML

<div id= "genre">
    What do you bust a move to?
    <form name="music" method="post" action="">
        <p>
        <input type="radio" name="music" value="radio" onBlur="changeColour("b")">Blues
        <input type="radio" name="music" value="radio" onBlur="changeColour("r")">Rock
        <input type="radio" name="music" value="radio" onBlur="changeColour("p")">Pop
    </form>
</div>

I am new to this so any help is welcome. Thanks.


Solution

  • You were close. I changed events to onclick and it's backgroundColor not Colour. Here's an example - http://jsfiddle.net/6jt8h/

    <div id= "genre">
    What do you bust a move to?
    <br>
    <br>
    <form name="music" method="post" action="">
    <p>
    <input type="radio" name="music" value="radio" onClick="changeColour('b')">Blues
    <br>
    <input type="radio" name="music" value="radio" onClick="changeColour('r')">Rock
    <br>
    <input type="radio" name="music" value="radio" onClick="changeColour('p')">Pop
    <br>
    </form>
    </div>
    
    
    function changeColour(value)
    {
        var color = document.body.style.backgroundColor;
        switch(value)
        {
            case 'b':
                color = "#FF0000";
            break;
            case 'r':
                color = "#0000FF";
            break;
            case 'p':
                color = "#FF00FF";
            break;
        }
        document.body.style.backgroundColor = color;
    }