I am brand new to HTML and JQuery, and I'm struggling with setting a class for my select element when the currently selected option has an ID of "answer". This is crucial for checking the correctness of a multiple choice question.
If achieving this in JQuery proves impossible, JavaScript would be an acceptable alternative. My goal is to avoid making a database query and leveraging JQuery seemed like the most efficient approach.
Below is the current HTML section I have:
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question </label>
<select class="form-control select-class">
<option value="1" class="ans-class" id="answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question </label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class" id="answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary"
onclick="checkAnswers()">Check</button>
</form>
A Javascript function called "checkAnswers()" is executed upon clicking the button.
This function is meant to verify if the selected option in the dropdown box has an id of "answer". Essentially, it should change the background color of the select element if the correct option (option one) is chosen.
How can I detect the currently selected dropdown option's ID? And how do I extend this functionality to multiple questions at once?
Additionally, how can I dynamically add a class to the select element using JavaScript in order to modify its background color?
Here is the JavaScript code snippet I attempted:
var s = document.getElementsByClassName("select-class");
var idSelectedOption = s[s.selectedIndex].id;
alert(idSelectedOption);
However, this resulted in an error message: "Uncaught TypeError: Cannot read property 'id' of undefined". I believe this occurs because it returns an array of classes. How would I iterate through all of them and alter the background colors of those with the correct option selected?
Thank you in advance,
Mats.