Reputation: 1850
I'm building a quiz app, and for a certain part of it I would like for some of the answers to be highlighted upon loading of the page.
These are the buttons:
<input type="hidden" name="correct_answer" value="<?php echo (isset($correct_answer)) ? $correct_answer : 'no corect answer';?>">
<button name="answer" value="A" class="btn btn-primary btn-lg">A</button>
<button name="answer" value="B" class="btn btn-primary btn-lg">B</button>
<button name="answer" value="C" class="btn btn-primary btn-lg">C</button>
<button name="answer" value="D" class="btn btn-primary btn-lg">D</button>
<button name="answer" value="E" class="btn btn-primary btn-lg">E</button>
You can see I'm loading a hidden element with the correct answer inside it.
All the back end works just fine, But I can't seem to figure out how to do this.
Is it possible to do this in native JS or is jQuery a must? Also, how do I go about doing this? How do I make sure the CSS class is added to the right element?
EDIT:
This is the code I ended up using:
<script type="text/javascript">
document.getElementById("<?php echo $correct_answer;?>").style.backgroundColor = "green";
</script>
Upvotes: 0
Views: 1799
Reputation: 91555
Since you're already rendering the page with PHP, why not just have it add a class to those elements you want highlighted.
<button name="answer" value="A" class="btn btn-primary btn-lg <?php if ($correct_answer === "A") { ?>highlight<?php } ?>">A</button>
Then style that class:
.highlight {
background-color: red;
}
Even if you were to use javascript to solve this, adding a class is far better than adding styles to an element. The class is more semantic and can be easily restyled without having to dig through your code.
Upvotes: 1
Reputation: 35670
Here's a pure JavaScript solution that will work with your existing HTML:
var correct= document.getElementsByName('correct_answer')[0].value;
var buttons= document.getElementsByName('answer');
for(var i = 0 ; i < buttons.length ; i++) {
if(buttons[i].value===correct) {
buttons[i].style.background= 'red';
break;
}
}
Fiddle at http://jsfiddle.net/qw7qhvnq/
Upvotes: 1
Reputation: 7666
You can do this with vanila javascript using the backgroundColor,
So your js code would look like:
document.getElementById("answer1").style.backgroundColor = "red";
Please note that I have set Id for one element, however you can set for all elements and use that Id whose background is to be changed.
Upvotes: 2