0

I'm trying to program a button that randomly picks a color from the color array and chooses between these four values, and the color will be given to a new element.

They're classes that are defined in css. It's not working properly though as I don't see the issue with what I'm doing.

  <script>
    var colorArray = [ '.st1', '.st2', '.st3', '.st4'];
    var randomColor = Math.floor(Math.random()*colorArray.length);
    </script>

      <label>
        Class: <input type="text" id="new-class" value="randomColor">
      </label>

  <button type="button" onclick="addObject()">
    Make Ball
  </button>

Can anyone see to what I'm doing wrong?

André Dion
  • 21,269
  • 7
  • 56
  • 60
ZoEM
  • 850
  • 9
  • 27
  • 2
    You cannot use JavaScript variables as values for HTML attributes like this. – Phylogenesis Aug 30 '16 at 16:02
  • are you trying to make your ball a random color? -- the value will not take on the javascript in your input... – wdfc Aug 30 '16 at 16:02
  • this won't fix your problem, but it is a next step into what you want... i think http://www.w3schools.com/jsref/prop_hidden_value.asp – wdfc Aug 30 '16 at 16:05
  • 1
    See [Change an element's class with JavaScript](http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript) – Alex K. Aug 30 '16 at 16:06

1 Answers1

1

To use a javascript variable as an HTML value, you have to set it in javascript. So to set your value attribute, do it like this: And you need to wrap the code in the function that you set in the onClick

<script>
    function addObject(){    
       var colorArray = ['.st1', '.st2', '.st3', '.st4'];
        var randomColor = Math.floor(Math.random() * colorArray.length);
        console.log(colorArray[randomColor]);
        document.getElementById("new-class").className = colorArray[randomColor];
    }
</script>
Luigi Cerone
  • 362
  • 1
  • 6
  • 18
M B
  • 2,326
  • 24
  • 33
  • 2
    I read the question as wanting to change the class of the element rather than the value. – Alex K. Aug 30 '16 at 16:07
  • I just showed him how to get the value of the variable in the place where he was trying to use it. In the html, it was a `value` attribute. you can set whatever atribute you want – M B Aug 30 '16 at 16:09