Reputation: 305
I am new to materialize.css and i actually i want to change the button color on click using javascript. Each button on click has to yield a different color depending on the button content. But when i click on he button it doesnt change it color.
<div class=" buttons row center-align">
<button class="btn col s12 m6 deep-purple darken-4 center-align" id='button0' onclick ="answer('0')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option0"></span></button><br>
<button class="btn col s12 m6 deep-purple darken-4 center-align" id='button1' onclick ="answer('1')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option1"></span></button><br>
<button class="btn col s12 m6 deep-purple darken-4 center-align" id='button2' onclick ="answer('2')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option2"></span></button><br>
<button class="btn col s12 m6 deep-purple darken-4 center-align" id='button3' onclick ="answer('3')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option3"></span></button><br>
</div>
javascript
function answer(ans){
var z = document.getElementById('option'+ans);
var choice = z.innerHTML;
var b = document.getElementById('button'+ans);
if(choice == questions[x].answer){
b.style.backgroundColor = '#008000';
b.style.color = 'rgb(255, 255, 255)';}
else{
b.style.backgroundColor = '#700000';
b.style.color = 'rgb(255, 255, 255)';}
Upvotes: 0
Views: 984
Reputation: 305
html
<div class=" buttons row center-align">
<button class="button col s12 m6 center-align" id='button0' onclick ="answer('0')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option0"></span></button><br>
<button class="button col s12 m6 center-align" id='button1' onclick ="answer('1')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option1"></span></button><br>
<button class="button col s12 m6 center-align" id='button2' onclick ="answer('2')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option2"></span></button><br>
<button class="button col s12 m6 center-align" id='button3' onclick ="answer('3')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option3"></span></button><br>
Just remove the materializecss button class 'btn' and replace with any name , i did with button and remove the materializecss color class inside the buttons tag, so finally each buttons will be of class:
'button col s12 m6 center-align'
and in self-created css file for this html file;(main.css)
.button.col.s12.m6.center-align{
background-color: #311b92;
padding: 10px 20px 10px;
border-radius: 50px;
font-size: 2em;}
and now when we apply the above javascript method mentioned in the question; the button color will change on click
Upvotes: 2