Ohad
Ohad

Reputation: 1631

how to create a group of radio buttons with JavaScript?

Does anyone know why this simple program doesn't work? It's a program that creates a group of radio buttons with Javascript.

<html>
  <head>
    <script>
      function onWriteRadio(Valuse,numButtons,RadioName){
        for(i=0;i<numButtons;i++){
          document.write("<input type='radio' name=" + RadioName + "value="       +Valuse[i]+"/>");
          document.write("<br/>");
        }
      }
    </script>
  </head>

  <body onload="onWriteRadio([red,green,blue],3,'color')>

  </body>
</html>

Upvotes: 1

Views: 136

Answers (5)

Marc Rubi&#241;o
Marc Rubi&#241;o

Reputation: 735

you left some quotation marks.

function onWriteRadio(values, radioName){
    
          for (var i = 0; i < values.length; i++) {
        document.write("<input type='radio' name='" + radioName + "' value='" +values[i]+"' >"+values[i]+" </ input>");
        document.write("<br/>");
    }
    }
<html>
  <body onload="onWriteRadio(['red', 'green', 'blue'], 'color')">

  </body>
</html>

Upvotes: 1

Denis O.
Denis O.

Reputation: 1850

  1. place array values in quotes
  2. add closing double quote for onload
  3. make one string containing all inputs code and then write it

Your code should look smthng like this:

<html>
<head>
<script>
function onWriteRadio(Valuse,numButtons,RadioName){
    var s = '';
    for(i=0;i<numButtons;i++){
        s += "<input type='radio' name=" + RadioName + "value="       +Valuse[i]+"/>"
    }
    document.write(s);
}
</script>
</head>
<body onload="onWriteRadio(['red','green','blue'],3,'color')">
</body>
</html>

Upvotes: 0

Sajad Karuthedath
Sajad Karuthedath

Reputation: 15767

put array values in quotes

onWriteRadio(['red','green','blue'],3,'color')

Upvotes: 2

james emanon
james emanon

Reputation: 11807

use this:

onWriteRadio(['red','green','blue'],3,'color')

string the array values. Currently, you say [red,green,blue], that means the variable red, variable green, variable blue, BUT you don't define them anywhere, so your program is saying "hmm, i do not know what red is.".. so string em.

Upvotes: 5

Linga
Linga

Reputation: 10555

document.write() writes HTML expressions or JavaScript code to a document, which replaes your earlier html content.

document.write() executed after the page has finished loading will overwrite the page, or write a new page.

document.write() is a bad practice

Upvotes: 0

Related Questions