Add a CSS class to a dropdown menu option in HTML and JavaScript (JQuery) if it has a specified ID

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.

Answer №1

It is advisable to use data-* attributes instead of id when dealing with multiple elements in a document sharing the same id value.

When using getElementsByClassName, it returns a nodelist, so you will need to iterate through the elements and apply conditions accordingly. In the example below, Array.prototype.forEach.call is used to iterate through elements.

Here's an example:

function checkAnswers() {
  var s = document.getElementsByClassName("select-class");
  Array.prototype.forEach.call(s, function(elem) {
    var idSelectedOption = elem[elem.selectedIndex].getAttribute('data-id');
    if (idSelectedOption == 'answer') {
      var selectedAnswer = elem[elem.selectedIndex].getAttribute('value');
      alert(selectedAnswer);
    }
  });
}
<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" data-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" data-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>

Link to the Fiddle here

Answer №2

Make sure not to have duplicate IDs for elements. Consider using custom data attributes or classes instead.

Once you've addressed that issue, the following code should work. I opted for vanilla JavaScript as you didn't specify jQuery usage.

// Lazy: Bind the event to the form.
document.getElementById('ansForm').addEventListener('change', function(event) {
  
  var selectElement = event.target;
  
  // Only respond if the clicked element is one of the selects.
  if (selectElement.classList.contains('select-class')) {
    
    // Get the option that is currently selected.
    var selectedOption = selectElement[selectElement.selectedIndex];
    // Check if this option contains the class 'answer'.
    var isAnswerSelected = selectedOption.classList.contains('answer');
    
    console.log(isAnswerSelected);
    
    // Remove the indicators. You could easily use classList.toggle, but the second
    // argument is not supported in IE.
    
    // selectElement.classList.toggle('right', isAnswerSelected);
    // selectElement.classList.toggle('wrong', !isAnswerSelected);

    // So, second best. Just remove both and re-add the class we want.
    selectElement.classList.remove('right');
    selectElement.classList.remove('wrong');
    selectElement.classList.add(isAnswerSelected?'right':'wrong');
    
  } else {
    // Ignore clicks on any other element.  
  }
});
.right {
  color: green;
}

.wrong {
  color: red; 
}
<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 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 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>

Answer №3

Here is a jQuery solution you can try:

$(function(){
    // Event handler for clicking the element with id 'checkBtn'
    $('#checkBtn').on('click', function(){

        // Get all select elements with class 'select-class'.
        var $selects = $('select.select-class');

        // Iterate through each select element.
        $selects.each(function(k, v){
            // Get the option with id 'answer' for the current select element.
            var $selectAnswerOpt = $(this).children('option#answer');

            // Get the value attribute of the option element.
            var answer = $selectAnswerOpt.attr('value');

            // Get the selected value for the select element.
            var selectedValue = $(this).val();

            // Check if the selected value matches the id 'answer'
            if (selectedValue == answer)
            {
                // Change background color to green if selected value matches 'answer'
                $(this).css('background-color', 'green');
            }
            else
            {
                // Change background color to yellow if not matching 'answer'
                $(this).css('background-color', 'yellow');
            }
        });
    });
});

Check out the FIDDLE for reference.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing API calls utilizing Axios in a NodeJS environment with the Authorization Basic feature

I have developed an API to retrieve a token from PayPal. curl -v POST https://api.sandbox.paypal.com/v1/oauth2/token \ -H "Accept: application/json" \ -H "Accept-Language: en_US" \ -u "CLIENT_ID:SECRET" &b ...

Is there a way to resolve issues with window.open() on Heroku platform?

I've been working on hosting a webpage on Heroku using Node.js. Instead of using the php method, I opted to go with Node and it's been going smoothly so far. However, I've run into a small issue. Here's what my Procfile looks like: web ...

Strange occurrences with the IMG tag

There seems to be an issue with my IMG element on the webpage. Even though I have set the height and width to 100%, there is some extra space at the end of the image. You can view the problem here: I have also included a screenshot from the developer too ...

Having trouble loading the socket.io.js file in electron

I am in the process of developing a chat application using Node.js, Electron, and Socket.io. However, I am encountering an issue when trying to load /socket.io/socket.io.js. Every time I attempt to do so, I receive the following error: Failed to load res ...

Customizing data from AJAX responses

Using PHP, I am receiving data as an object and passing it through a mustache template to create a table. My inquiry is about controlling the row breaks for my data. Is there a way to insert a <tr> after every 3 <td> without using JavaScript? Da ...

The npm request was unsuccessful due to a self-signed certificate within the certificate chain causing the failure

I am attempting to launch a React Native project using Expo from this site npm install expo -g expo init AwesomeProject npm start However, when running npm start, I encounter the following error: npm ERR! code SELF_SIGNED_CERT_IN_CHAIN npm ERR! er ...

The main.js file will be served by nodeJS using express

After developing a nodeJS server using express, I encountered an issue where the server was only delivering the index.html file and not the accompanying main.js file. Both files are located in the same directory. app.get('/', function (req, res) ...

I tried moving the onchange(this) function from HTML to JavaScript, but I seem to have missed a parameter. The code ends

I'm currently building a website for a fictional ice cream shop to enhance my JavaScript skills. function hideAAndB() { var pickupDiv = document.getElementById("pickupDiv"); var deliveryDiv = document.getElementById("deliveryDiv"); pickupDi ...

What is the process for accessing a table in indexedDB using Dexie.js immediately after it has been opened?

I am faced with the challenge of needing to verify if a specific table already exists in IndexedDB right after it has been opened. However, I am unsure how to access the DexieDB object inside the 'then' statement. this.db = new Dexie("DBNAME"); ...

Retrieve dashboard configurations in AngularJS by making an $http request prior to initiating the dashboard controller

I am currently immersing myself in Angular and tackling a complex dashboard framework all built with Angular. Prior to loading the controllers, I need to fetch various dashboard settings from the server using $HTTP. These settings play a crucial role in de ...

Enable the button if at least one checkbox has been selected

I've written some code similar to this: $('input[type=checkbox]').click(function(event) { $('.chuis').each(function() { if(this.checked) { $('#delete_all_vm').prop("disabled",false); } ...

What is the best way to show instructions immediately upon receipt of a response?

I'm currently working on developing a website similar to ChatGpt using the OpenAI API for GPT. However, there is a delay in generating responses with GPT taking a few seconds. As a result, my code only displays the instruction once the response from G ...

How about this: "Looking to Share on Social Media with ME

After developing an app using MEAN.js, I made enhancements to the Articles (blog) section to improve SEO, readability, and design. However, one issue I'm struggling with is how to properly share these Articles on social media platforms like Facebook, ...

JavaScript is able to access the HTML content of the previously opened tab when saving the window

Seeking advice from the knowledgeable community at Stack Overflow! I have a project that I'm unsure how to start, and I could use some fresh ideas. My goal is to access the HTML source code of a previously opened tab or one that is still loading on m ...

Strange symbols keep appearing in my output from PHP

My current task involves generating a SQL query based on some inputs. I have a predefined SQL statement, in which I perform certain replacements, that will use these inputs to generate the required SQL through an ODBC connection. For now, I have stored th ...

Encountering difficulties while trying to install ng2-material in Angular 2

I'm attempting to utilize a data table with the ng2-material library from ng2-material as shown below: <md-data-table [selectable]="true"> <thead> <tr md-data-table-header-selectable-row> <th class="md-text-cell">M ...

Is Valums Ajax file Upload capable of handling the uploaded file?

Currently, I am utilizing the Valums Ajax Fileupload script found at These are the settings I have configured: function createUploader(){ var uploader = new qq.FileUploader({ element: document.getElementById('file-uploader-de ...

Field for user input along with a pair of interactive buttons

I created a form with one input field and two buttons - one for checking in and the other for checking out using a code. However, when I submit the form, it leads to a blank page in the php file. What could be causing this issue? UPDATE After changing fro ...

The issue of javascript Map not updating its state is causing a problem

I've encountered an issue where my components are not re-rendering with the updated state when using a map to store state. const storage = (set, get) => ({ items: new Map(), addItem: (key, item) => { set((state) => state.items ...

Constructing a Primeng MessageService causes a blank webpage to appear

After downloading the QuickStart CLI of PrimeNG for Angular, I added a second component for a chart that was already included in the UI components. Everything seemed to be set up correctly, but when I saved, I ended up with a completely blank page for the ...