admin管理员组

文章数量:1313095

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 wele. Thanks.

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 wele. Thanks.

Share Improve this question edited Jul 2, 2022 at 10:10 Jonas 129k102 gold badges327 silver badges405 bronze badges asked Nov 20, 2013 at 17:27 user3014211user3014211 32 gold badges2 silver badges3 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 1

You were close. I changed events to onclick and it's backgroundColor not Colour. Here's an example - http://jsfiddle/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;
}
  1. do not have html between the statements. Remove the <br>

  2. pass the value in single quotes and use it in the function declaration

  3. use onclick and not onblur

  4. value="radio" is not useful

  5. color is spelled in American English in the javascript. Your function name may be spelled changeColur but backgroundColor must be with o. That means your html would be
    <input type="radio" name="music" value="radio" onClick="changeColour('b')">Blues

  6. add label so user can click on the text too

It is considered good practice to wrap in {} so

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

Here is how I would code it

Live Demo

<!doctype html>
<html>
<head>
<meta charset="utf.8" />
<title>Rock 'n Roll</title>
<script>
var cols = {
  "r":"#FF0000",
  "b":"#0000FF",
  "p":"#FF00FF"
} // no ma after the last
window.onload=function() { // when the page loads
  var rads = document.getElementsByName("music"); // all rads named music
  for (var i=0;i<rads.length;i++) {
    rads[i].onclick=function() {
      document.body.style.backgroundColor=cols[this.value];
    }
  }
}
</script>
</head>
<body>
<div id= "genre">
  What do you bust a move to?
  <br>
  <br>
  <form name="music" method="post" action="">
  <input type="radio" name="music" id="bRad" value="b"><label for="bRad">Blues</label>
  <br>
  <input type="radio" name="music" id="rRad" value="r"><label for="rRad">Rock</label>
  <br>
  <input type="radio" name="music" id="pRad" value="p"><label for="pRad">Pop</label>
  <br>
  <br>
  </form>
</div>
</body>
</html>

Should be like this :

<form name="music" method="post" action="">
<p>
<input type="radio" name="music" value="radio" onBlur="changeColour('b');">Blues
<br>
<input type="radio" name="music" value="radio" onBlur="changeColour('r');">Rock
<br>
<input type="radio" name="music" value="radio" onBlur="changeColour('p');">Pop
<br>
</form>


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

I'd strongly suggest removing your JavaScript from your HTML, and using JavaScript to bind the event-handling (which makes for more easily maintainable code, since you don't have to hunt through HTML to update/change anything; it should all be in the JavaScript file/library that you implement). That said, I'd suggest the following HTML:

<div id="genre">What do you bust a move to?
    <form name="music" method="post" action="#">
        <input type="radio" name="music" value="radio"/>Blues
        <input type="radio" name="music" value="radio" />Rock
        <input type="radio" name="music" value="radio" />Pop</form>
</div>

With the following JavaScript:

function changeColour (e) {
    // e.target is the element that triggered the event we're reacting to:
    var el = e.target;
    /* el.nextSibling.nodeValue is the text of the next sibling-node,
       toLowerCase() turns that text into lower-case,
       [0] gets the first letter of that text:
    */
    switch (el.nextSibling.nodeValue.toLowerCase()[0]) {
        case 'b' :
            // 'this' is the element that's handling the event (the div):
            this.style.backgroundColor = '#00f';
            break;
        case 'r' :
            this.style.backgroundColor = '#f00';
            break;
        case 'p' :
            this.style.backgroundColor = '#f0f';
            break;
    }
}

/* gets the element with the id of 'genre', and adds a listener to that
   element, listening for the change event, and triggering the 'changeColour' 
   function when it's detected:
*/
document.getElementById('genre').addEventListener('change', changeColour, true);

JS Fiddle demo.

Further, I'd suggest wrapping the input elements with label elements, in order that clicking on the label (the text itself) is able to check the associated input for that text:

<div id="genre">What do you bust a move to?
    <form name="music" method="post" action="#">
        <label>
            <input type="radio" name="music" value="radio" />Blues</label>
        <label>
            <input type="radio" name="music" value="radio" />Rock</label>
        <label>
            <input type="radio" name="music" value="radio" />Pop</label>
    </form>
</div>

JS Fiddle demo.

It's also possible to use a JavaScript object to associate the choices with colours, for example:

function changeColour(e) {
    // sets the letter-colour options:
    var colorMap = {
        'b' : '#00f',
        'r' : '#f00',
        'p' : '#fof'
    };
    var el = e.target,
        checked = el.nextSibling.nodeValue.toLowerCase()[0];
    /* if the relevant letter is in the colorMap object
       (and generates a truthy value), we set the background-color
       to whatever is retrieved:
    */
    if (colorMap[checked]){
        this.style.backgroundColor = colorMap[checked];
    }
}

document.getElementById('genre').addEventListener('change', changeColour, true);

JS Fiddle demo.

本文标签: javascriptChange background color using radio buttonsStack Overflow