Customize checkbox and label using jQuery

I have a scenario where I have multiple checkboxes and corresponding labels. When the answer is correct, I want to change the background color of the selected checkbox and label.

<input type="checkbox" id="a" class="check-with-label" />
<label for="a" class="question_box">
    <?php echo $vraag[0]['A'] ?>
</label>

<input type="checkbox" id="b" class="check-with-label" />
<label for="b" class="question_box">
    <?php echo $vraag[0]['B'] ?>
</label>

Upon submitting, an ajax call is made to a script to validate the answer.

$('#bottom').on('click', function(){
    $('#antwoorden input:checked').each(function() {
        var selected = $(this).attr('id');
        selected = selected.toUpperCase();

        var data = {
            vraag_nummer : <?php echo $vraag[0]['id'] ?>,
            antwoord     : selected
        };

        console.log(data);
        $.ajax({
            type: 'POST',
            url : 'includes/check_correct.php',
            data: data,
            success: function(data) {
                if(data.correct){
                    this.css('background-color', 'green');
                } else {
                    this.css('background-color', 'red');
                }
            },
            error: function(err) {
                console.log('error');
                console.log(err);
            }
        });
    });
});

The challenge lies in identifying the correct box since upon submission, the 'this' variable refers to the submit button rather than the checked box. There can only be one checkbox selected at a time.

How do I change the background color to green (and red for incorrect answers) based on the selection?

.check-with-label:checked + .question_box {
    background-color: orange;
} 
background-color:green

(For incorrect, use red)

Answer №1

Consider updating the label rather than this

You've already obtained the ID of the label

(

var selected = $(this).attr('id');
)

This will likely result in a/b/c/d and then utilize

$('label[for="'+selected+'"]').css('background-color', 'green'); //or red if else statement is true

which modifies the label for the selected id, which in this case is d the code above essentially translates to:

$('label][for="d"].css('background-color','green'); //or red

but using the chosen variable instead

Best of luck!

Answer №2

When achieving success, opt for selected_obj.css over this.selected and pass $(this) to selected_obj

$('#bottom').on('click', function(){
    $('#antwoorden input:checked').each(function() {
        var selected = $(this).attr('id');
        var selected_obj = $(this);
        
        selected = selected.toUpperCase();

        var data = {
            vraag_nummer : <?php echo $vraag[0]['id'] ?>,
            antwoord     : selected
        };

        console.log(data);
        $.ajax({
            type: 'POST',
            url : 'includes/check_correct.php',
            data: data,
            success: function(data) {
                if(data.correct){
                    selected_obj.css('background-color', 'green');
                    
                } else {
                    selected_obj.css('background-color', 'red');
                }
            },
            error: function(err) {
                console.log('error');
                console.log(err);
            }
        });
    });
});

Answer №3

Give this a try

$('#bottom').on('click', function(){
    $('#antwoorden .check-with-label').each(function() {
        var chosen = $(this).attr('id');
        var isChecked = $(this).is(':checked'));
        if (!isChecked) {
            return;
        }
        var selected_obj = $(this);
        //var selected_box = this;
        chosen = chosen.toUpperCase();

        var data = {
            question_number : <?php echo $question[0]['id'] ?>,
            answer     : chosen
        };

        console.log(data);
        $.ajax({
            type: 'POST',
            url : 'includes/check_correct.php',
            data: data,
            success: function(data) {
                if(data.correct){
                    selected_obj.css('background-color', 'green');
                } else {
                    selected_obj.css('background-color', 'red');
                }
            },
            error: function(err) {
                console.log('error');
                console.log(err);
            }
        });
    });
});

Answer №4

Once the webpage is loaded and shown to the user, PHP stops running. This means that any PHP code inside your $('#bottom').on('click' function will not be executed. To work around this, you can store the necessary information during page construction, such as by embedding it in a data attribute.

In the AJAX success function, the $(this) object cannot be accessed directly. To overcome this, assign it to a global variable so that you can retrieve its value when needed.

/* javascript/jQuery */
$('#bottom').on('click', function(){
    $('#antwoorden input:checked').each(function() {
        var selected = this.id; //faster, same result
        $this = $(this);
        selected = selected.toUpperCase();

        var data = {
            //change next line - PHP finished running
            vraag_nummer : $this.attr('data-vn'),
            antwoord     : selected
        };

        console.log(data);
        $.ajax({
            type: 'POST',
            url : 'includes/check_correct.php',
            data: data,
            success: function(data) {
                if(data.correct){
                   $this.css('background-color', 'green');
                } else {
                   $this.css('background-color', 'red');
                }
            },
            error: function(err) {
                console.log('error');
                console.log(err);
            }
        });
    });
});
<!-- HTML: -->
<input id="vraag_nummer" data-vn="<?php echo $vraag[0]['id'] ?>" type="text" />

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

Prevent mobile view from activating when zoomed in on the screen

I've built a webpage with a responsive design that adjusts to mobile view on mobile devices or when the screen size is reduced using developer tools. While this functionality works correctly, I have noticed that the design also switches to mobile vie ...

Bootstrap Progress Animation Not Scaling Properly

I am encountering an issue with my Bootstrap 2.3 progress bars. They are supposed to show async file reads and be animated by updating their CSS properties using jQuery. However, the problem I'm facing is that the scale seems to be off - when the prog ...

Upon submission of the form, trigger an email to be sent and simultaneously open a

I need my form to simultaneously open a window and send the form data via email when submitted. <form action="" method="post" id="form" onsubmit="paymentfunc();return false;"> Submit button: <input type="submit" value="Purchase" class="btn" id= ...

iOS devices experiencing issues with fixed positioning

Currently, I am in the process of implementing a few instances of , but I am encountering some issues with the CSS. When viewing the website on an iPad or iPhone, the calendar is positioned correctly as the container covers the window like a fixed position ...

If the index is greater than 0, then continue looping; otherwise, execute only once using JSON and jQuery

After customizing a jQuery paging script that I found on Paging Through Records Using jQuery, the paging functionality is working well. It can handle different javascript responses effectively. However, there is one issue. The response expects the JSON to ...

Tips on how to showcase a picture with the focus on the center by enlarging it within

We have a long frame on the page, with an aspect ratio of about 3.5:1 width to height. However, most of the photos being displayed are in a 4:3 ratio, which is larger and not a proper fit for the frame. The customer really wants the long frame and has no ...

Showing a collection of objects in a React component

**Recently started learning React and Node, and decided to fetch data into a functional component by following various tutorials. I successfully set up the server, connected it to the database, and fetched the data in React as per the tutorial instruction ...

Tips for implementing the same autocomplete feature across multiple form fields

Struggling to add multiple products and provide auto-suggest for each product name? You're not alone. It seems like the auto suggest feature is only working for the first product. Can anyone point out what's going wrong here? Here's my HTML ...

Encountering a 404 error in Codeigniter when making an AJAX call

After successfully implementing an upload form with ajax, I encountered some issues when attempting to delete uploaded photos. Initially, I received a "csrf protection error," which led me to disable csrf protection, only to then encounter a "404 not found ...

Potential Performance Issue with Material UI's withStyles Function

I've been given the task of optimizing the loading speed of a page in our react redux web app. When the page load action is triggered, there seems to be a slight freeze lasting about half a second. After checking the profiler, everything seems fine ...

Troubleshoot: Json causing issue with displaying markers on Google Maps API (v3)

I developed a custom Google Maps application using JSON data and implemented PostgreSQL database integration. Here is the code snippet: <script type="text/javascript"> var map; var national = [{"lng":"-6.173319","city":"JAKARTA","lat":"106.818 ...

Bx slider - displaying partially hidden slides at the far right while utilizing a full-width carousel

Implementing a slider on my nodejs website using bx slider has been quite an experience. Below is how I achieved it: $(document).ready(function(){ $(".bxslider").bxSlider({ minSlides: 1, maxSlides: 40, slideWidth: 300, ...

What sets TypeScript apart from AtScript?

From what I understand, TypeScript was created by Microsoft and is used to dynamically generate JavaScript. I'm curious about the distinctions between TypeScript and AtScript. Which one would be more beneficial for a JavaScript developer to learn? ...

What is the process of memory allocation for variables in Javascript?

Can you explain to me how local variables are allocated memory in JavaScript? In languages like C and C++, local variables are typically stored on the stack. Is this also the case with JavaScript, or are all variables stored in the heap? ...

Unable to retrieve JSON using the getJson method

I've been transitioning to using jQuery exclusively, but I can't seem to get this function to work. My JSON file is pretty simple: { "status": "active" } All I'm trying to do is check if something has switched on or off. I created a basic ...

Obtain the HTML of a Vue component and transmit it using an ajax POST request

I need to send an email with an HTML body using only ajax since I don't have access to the server code. Fortunately, the server has an API for sending emails. Currently, I have a dynamically rendered component called invoiceEmail. sendEmail () { ...

What steps can be taken to repair the script?

https://jsfiddle.net/fnethLxm/10/ $(document).ready(function() { parallaxAuto() }); function parallaxAuto() { var viewer = document.querySelector('.viewer.active'), frame_count = 5, offset_value = 500; // init control ...

Arrangement using the display property of inline-block not following a linear direction

I'm experiencing some issues with the arrangement of elements on this page: When the viewport width is around 800px, the layout appears misaligned. Some lines have only a few bottles even though there is space for more. Is there a solution to this pr ...

Troubleshooting issue: jQuery not functioning as expected when used in

Currently, I have implemented a jQuery script that utilizes an ajax update method triggered by the focus event of a form element. The functionality is operational; however, I am encountering an issue when attempting to validate if the form element is empty ...

Provide a spider with unadulterated HTML rather than setting off AJAX requests

While my website is being crawled, which PHP function should I utilize to ensure that even if ajax isn't activated, my content still gets transmitted? PHP doesn't have the ability to determine if ajax is supported. Objective: Provide the crawle ...