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

As I go through the database, I notice that my div model functions correctly for the initial record but does not work for any subsequent ones

I came across a model on w3 schools that fits my requirements, but I am facing an issue where the model only works for the first result when looping through my database. It's likely related to the JavaScript code, but I lack experience in this area. C ...

Component fails to re-render after token refresh on subsequent requests

Here is my axios-hoook.js file, utilizing the axios-hooks package. import useAxios from 'axios-hooks'; import axios from 'axios'; import LocalStorageService from './services/local-storage.service'; import refreshToken from &ap ...

Adjust the stroke and fill color of an SVG upon hovering over it

I have a unique SVG image with an intricate stroke around it that matches the color of a filled icon. Positioned on a black background within the image, you can view my example here: https://jsfiddle.net/o48629qs/ The challenge I am facing involves changi ...

Summoning within a rigorous mode

I am facing an issue with my configuration object: jwtOptionsProvider.config({ tokenGetter: (store) => { return store.get('token'); }, whiteListedDomains: ['localhost'] }); In strict mode, I ...

Struggling with z-index or float issues on Chrome and Safari with CSS styling

Check out my website at I have incorporated the Easy Slider 1.7 plugin from this source and made some custom JavaScript modifications for a banner rotator. The issue I am facing is that on webkit browsers, the navigation links (1,2,3,4,5) on the banner a ...

Initiate requests to external servers from a NodeJS backend

My NextJS application seamlessly collaborates with a NodeJS server to act as the front end of my innovative three-tier architecture. 'use client'; import FormControl from '@mui/material/FormControl'; import InputLabel from '@mui/m ...

Retrieving information from Flask server using an Ajax request

Exploring Flask and Ajax, my server-side web application is meant to double and return a passed number. I adapted the code from the example on Flask's site, resulting in this Python snippet: from flask import Flask, request, jsonify # Initialize the ...

What is the method for accessing a variable that has been defined within server.js from within my ejs script tag?

Currently working on my first NodeJS project which involves a significant amount of file management. I've been thinking about how to streamline the process by accessing a variable created in my server.js within a script tag inside one of my ejs files. ...

Looking for assistance with fixing the echo issue in my PHP temperature converter script. Any help is greatly appreciated

Below is my PHP code for converting temperatures: <html> <head> <title>Temperature Conversion</title> <meta charset="utf-8"> </head> <body> <form name="tempConvert" method=&q ...

The div is lacking in height

I have 3 divs that belong to the stackContainer class: .stackContainer { position: relative; } Within these divs, I want multiple elements stacked on top of each other. To achieve this, I use the following code: .stackItem { position: absolute; ...

Using jQuery to show and hide elements on a webpage

One issue I'm facing is changing the content on a page depending on the clicked link. The problem arises when the displayed content for one link persists even after clicking another link, despite setting it to not display when another link is clicked. ...

The AngularJS ng-repeat filter boasts dual parameters that vary based on the scope implemented

Two different instances of the same filter are causing unexpected outputs in my ng-repeat display. One instance is scoped at the app level and defined in the module, while the other is scoped at the controller level. Interestingly, when using the filter f ...

Is SWR failing to provide outdated data?

My understanding was that SWR should display the cached data upon page load before refreshing with new information from the API. However, in my Next.js app with a simple API timeout, the "loading" message appears every time due to the 5-second delay I adde ...

Firefox is mistakenly interpreting a pasted image from the clipboard as a string instead of a file, causing

I am facing an issue where I am attempting to extract images from a contenteditable div using the paste event. The code works perfectly in Chrome but does not function as expected in Firefox. I have implemented the following code: $(window).on("paste& ...

What methods can be used to identify the pattern entered by the user for data types such as `Int`, `VarChar`, `

I have a dropdown menu containing data types. There is also a text box for entering Regex patterns. If "/test/" is entered in the textbox or "Int" is selected from the dropdown, then it's an incorrect pattern. If "/[0-9]/" is entered in the ...

Use bracket notation to verify if a property is undefined

Having some difficulty determining if the property value of an object is undefined when accessed dynamically with bracket notation. Here's a snippet of my code: function toBritishDate(date: Date | string): string { console.log(date) return &qu ...

Can a before hook ever run after a test in any situation, Mocha?

My before hook runs after the initial test and at the conclusion of the second test. Here is the code for my before hook: before(function () { insightFacade.addDataset("courses", content) .then(function (result: InsightResponse) { ...

The data being sent from Ajax to the controller is not successfully transmitting the value to the controller

I've encountered issues trying to pass JSON data into an MVC controller. In the controller method, the property is defined as newObject like this: [HttpPost] public ActionResult Create(NewObject newObject) { try { //_deviceMangemen ...

What is the best way to determine the number of dimensions in a JavaScript array?

Take a look at this array and its corresponding expected output: In Javascript, is it possible to dynamically determine how many levels there are in the array ary? var ary = ["a","b",["c","d"],"e",["f","g",["h","i"],"j"]]; Output: 3 var ary = ["a","b",[" ...

Guidelines for utilizing React to select parameters in an Axios request

As a newcomer to ReactJs, I am working with a Product table on MySQL. I have successfully developed a dynamic table in the front-end using ReactJS along with MySQL and NodeJs on the backend. The dynamic table consists of four columns: Product, Quantity, Pr ...