Javascript alert function for confirming background color

Options are displayed in blue, and using JavaScript, I check if the background color is blue. If it's not, execute the next step; otherwise, display an alert message.

function click_option_A() {
var clr_1_chk = document.getElementById("1");
//alert(clr_1_chk.style.backgroundColor);
var clr_2_chk = document.getElementById("2");
var clr_3_chk = document.getElementById("3");
var clr_4_chk = document.getElementById("4");
if(clr_1_chk.style.backgroundColor !== "blue"){
alert("You have already selected this option!")
}
else if(clr_2_chk.style.backgroundColor !== "blue"){
alert("You have already selected this option!");
}
else if(clr_3_chk.style.backgroundColor !== "blue"){
alert("You have already selected this option!");
}
else if(clr_4_chk.style.backgroundColor !== "blue"){
alert("You have already selected this option!");
}
else{
var answer = "A";
    var confirm = window.confirm("Are you sure?");
    if (confirm) {
window.document.getElementById(answer).style.backgroundColor ="yellow";
var correct_answer = "B";
if(correct_answer == "A"){
//correct_ans();
setTimeout(correct_ans,3000);
}
else{
setTimeout(wrong_ans,3000);
}
}
}
}

// Repeat similar functions for options B, C, and D

function correct_ans(){
// Code for displaying correct answer
}

function wrong_ans(){
// Code for displaying wrong answer
}
td{
background-color: blue;
color: white;
}
<div class="container">

<table class="table table-bordered table-responsive">

    <tr class="text-center">
    <td colspan="2">Who was First Prime Minister of India?(15304)</td>
    </tr>
    <tr>
    <td id="1" onclick="click_option_A()">A) M K Gandhi</td>
        <td id="2" onclick="click_option_B()">B) Jawaharlal Nehru</td>
    </tr>
    <tr>
    <td id="3" onclick="click_option_C()">C) Rajendra Prasad</td>
<td id="4" onclick="click_option_D()">D) Chandra Shekhar Azad</td>
    </tr>
    
    </table>

</div>

I attempted to use the provided code, but it consistently alerts me that I've made a selection even when I haven't.

The choices are styled in blue, and my script aims to validate the color before proceeding with the action. It will display an alert message if the color is not blue.

Answer №1

One possible reason for not seeing the style as blue here, but rather an empty string, is because the element.style property only returns inline stylings and not those defined by CSS.

If you require CSS styling, you would need to obtain computed styles using

window.getComputedStyle(<element>)
.

For more information, visit MDN

In the code snippet below, I have added inline styling for td, which is why you will see the style as blue.

// JavaScript functions for handling user options
function click_option_A() {
    // Check if option A is selected
    var clr_1_chk = document.getElementById("1");
    // Check for other selected options
    // Display appropriate message or take action
}

// Repeat similar functions for options B, C, and D

// Function to handle when correct answer is chosen
function correct_ans() {
    // Based on color coding, identify correct answer and apply green background
}

// Function to handle when wrong answer is chosen
function wrong_ans() {
    // Based on color coding, identify wrong answer and apply red background
}
td {
    background-color: blue;
    color: white;
}
<div class="container">
    <table class="table table-bordered table-responsive">
        <tr class="text-center">
            <td colspan="2">Who was First Prime Minister of India?(15304)</td>
        </tr>
        <tr>
            <td id="1"  style="background-color: blue;color: white;" onclick="click_option_A()">A) M K Gandhi</td>
            <td style="background-color: blue;color: white;" id="2" onclick="click_option_B()">B) Jawaharlal Nehru</td>
        </tr>
        <tr>
            <td style="background-color: blue;color: white;" id="3" onclick="click_option_C()">C) Rajendra Prasad</td>
            <td style="background-color: blue;color: white;" id="4" onclick="click_option_D()">D) Chandra Shekhar Azad</td>
        </tr>
    </table>
</div>


It is recommended to maintain a JS object to track the options and provide the correct answer, instead of relying on object styles to determine the user's selection.

Answer №2

Although Prajwal's response is heading in the right direction, it falls short of completion. When calling getComputedStyle(), an RGB value is returned for backgroundColor. It is essential to compare this value instead of the string "blue". Therefore, in your scenario, use

getComputedStyle(clr_1_chk).backgroundColor === "rgb(0, 0, 255)";

For best practices, consider storing your questions in an array of JavaScript objects. This approach allows you to keep track of correct answers and question lock status. To demonstrate this concept, I have provided a quick dummy example below. While I omitted the setTimeout as per your request, adding it should be straightforward. Ensure that you integrate HTML, CSS, and JS components for seamless operation. Note that the error message after question 4 indicates the absence of further questions to generate. Here is how your code snippet could look:

// Your array of questions with corresponding details
var questions = [...];

// Function to generate each question
function generateQuestion(question) {
  // Implementation logic here
}

// Handling user selection of answer options
function onSelect(e) {
  // Selection handling implementation
}

// Initiate the test by generating the first question
function startTest() {
  // Initialization logic here
}
.correct {
  background-color: green;
}

.incorrect {
  background-color: red;
}
<div id="start"></div>
<table id="test"></table>

The updated snippet from your query has been corrected to function correctly. Although not reflected in my response, renaming your ids using letters [A-Za-z] is highly recommended.

... Your corrected JavaScript code snippet goes here. ...

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

Is there a way for me to determine the exact coordinates of all buttons on a given webpage?

I came across this piece of code, but I'm a bit unsure about where exactly I should input it and how to adjust it to locate the position of each button. Additionally, I'm curious as to where the results (coordinates) will be shown? function find ...

What is the method for gaining access to variables and functions within bundle.js?

Hello, I am trying to figure out how to access variables in bundle.js. I want to experiment with variables and functions on the client side using JavaScript, but I'm having trouble calling them in index.html or the Chrome console. I use browserify to ...

Async Autocomplete fails to display options if the label keys do not match the filtering keys

While I have experience with ReactJs and Material UI, I encountered a surprising issue. I am using the Material-UI Autocomplete component as shown below. The users variable is an array of objects. When searching for firstName or lastName in the user table, ...

Tips for managing modal states in functional React components in React Native using React hooks

Utilizing React hooks to manage modal opening and closing, I encountered an issue with my code. The function 'handleAddClick' is supposed to open the modal when used on TouchableOpacity, while the function 'handleClose' should close the ...

Access the $event object from an Angular template selector

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <input type="file" #myFile multiple /> <button (click)="onDelete(myFile.event)">DeleteFiles</button> My code snippet is experienci ...

AngularJS: How to detect the browser's refresh event

Can AngularJS detect when the user clicks the Refresh button on the browser? Is there a built-in method in the framework for developers to access? Thank you ...

What is the best way to execute a randomly chosen function in JavaScript?

I need help running a random function, but I'm struggling to get it right. Here's what I have so far: <script> function randomFrom(array) { return array[Math.floor(Math.random() * array.length)]; } function randomchords(){ randomFrom ...

What impact does setting a variable equal to itself within a Dom Object have?

Within my code example, I encountered an issue with image sources and hrefs in a HTML String named tinymceToHTML. When downloading this html String, the paths were set incorrectly. The original image sources appeared as "/file/:id" in the String. However, ...

Shifting the key of a choropleth map with R, rMaps, and datamaps

My challenge is to center the legend below a choropleth map of the United States. I don't have much experience with JS or CSS, but I decided to delve into the datamaps.all.min.js file in the R-3.2.1\library\rMaps\libraries\datamaps ...

The React Query devtools are failing to display

I am currently working on a project using React Query, but for some reason, the DevTools icon is not appearing on my screen. I have checked the console for errors, but there are none. I am following a tutorial on YouTube to help me with this. Here is a sn ...

Utilize ModifyDOM to erase text triggered by selecting a radio button

I have created a form that includes four radio buttons along with a reset button to clear the form. When a radio button is selected, information is displayed using "displayText". I am looking to add an onclick handler to trigger a function that will delete ...

Using Iron Router to incorporate CSS animations with onBefore and onAfter actions

Is there a way to enable animations using iron router? A css class is applied when a page is loaded The css animation library used is animate.css The animation works the first time but doesn't repeat when navigating to other pages. router.coffe ...

Setting a fixed height for layout with scroll functionality in Twitter Bootstrap 3.2.0

I am currently working on a design layout using bootstrap 3.2.0. I have managed to create a Fixed header and footer, and I am now facing the challenge of having a full-height container with independent scrollbars. Are there any effective methods in Twitter ...

What techniques can I use to modify an object while it's being iterated through?

I've been attempting to manipulate the object while looping through it, but unfortunately, it's not working. How can I modify it so that the constant patient includes the property lastActivity inside the this.model array? My code looks like this ...

What could be causing the inconsistency in triggers for the "keypress" event handler?

Help needed with a function I'm working on. The issue is that it doesn't seem to be firing properly. While the function does work, there's an anomaly - when I try to change the quantity value in the form (which defaults to 1), and let's ...

Choosing a portion of a polyline - Google Maps Application Programming Interface

Is it possible to select only a section of a polyline in a Google Map? I have markers that are added by the user and a polyline is drawn between the markers. The polyline between two markers represents the route between the two places. I want the user to b ...

Employing fetch to send a POST request for inserting data into a JSON server database

I'm currently experimenting with adding new data to my simulated database using JSON server. However, I've encountered an issue where the input information is not being added when I execute the function. Although an ID is generated in my databas ...

Generate a unique JavaScript token using user-specific information

I am in need of a unique identifier for users that can be generated without conflicting with other users' tokens. One idea I had was creating a token using the MD5 hash of navigator.userAgent + new Date().getTime(). However, I don't want to use a ...

What is the best way to incorporate and execute a separate JavaScript file in a Node application using Express JS?

I am attempting to configure a javascript file that is responsible for grabbing an RSS feed and storing the information in a database. Originally, I had this file called by the HTML page, but now I want it to continuously run in the back-end (constantly re ...

Utilizing the spread operator to map an array within another array

Exploring the spread operator inside an array to map values from another array has led to unexpected behavior. When attempting to return 2 objects using map within the array, only the last object is being returned. Below is the code snippet: const cats = [ ...