Implementing checkbox selection to dynamically alter button color

I have 5 rows of green buttons, each row containing 30 buttons. When a button is clicked, a modal pops up with a checkbox inside. If the checkbox is checked, I want the button to change to red. I've tried a few methods, but none have been successful. Any suggestions on how to achieve this?

Sample HTML:

            <button type="button" class="btn btn-primary btn-xs gridbtn" data-toggle="modal" data-target="#myModal">number</button>

            <!-- Modal -->
            <div class="modal fade" id="myModal" role="dialog">
                <div class="modal-dialog">

                    <!-- Modal content-->
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                            <h4 class="modal-title">Testing</h4>
                        </div>
                        <div class="modal-body">
                            <form role="form">
                                <div class="form-group">
                                    <label for="email">Email address:</label>
                                    <input type="email" class="form-control" id="email">
                                </div>
                                <div class="form-group">
                                    <label for="pwd">Password:</label>
                                    <input type="password" class="form-control" id="pwd">
                                </div>
                                <div class="checkbox">
                                    <label><input type="checkbox"> Remember me</label>

                                </div>
                                <button type="submit" class="btn btn-default">Submit</button>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>

Answer №1

Here are some tips for enhancing your HTML:

Give each button a unique id:

<button id="btn1" type="button" class="btn btn-primary btn-xs gridbtn" data-toggle="modal" data-target="#myModal">number</button>
<button id="btn2" type="button" class="btn btn-primary btn-xs gridbtn" data-toggle="modal"  data-target="#myModal">number</button>
<button id="btn3" type="button" class="btn btn-primary btn-xs gridbtn" data-toggle="modal" data-target="#myModal">number</button>

Assign a class to your checkbox element:

<div class="checkbox callback-to-button">

Check out the JavaScript section for additional functionality:

$('#myModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget); // Button that triggered the modal
  $(this).find('.modal').attr('data-triggered', $(button).attr('id'));
})

$('.callback-to-button').click(function() {
    var target = $(this).closest('.modal').attr('data-triggered');
    if ($(this).find('[type=checkbox]').prop('checked')) {
        $('#'+target).css('background-color', 'red');
    }
    else {
        $('#'+target).css('background-color', '');
    }
});

View the live demonstration here: here

Answer №2

In order to achieve your desired outcome, utilizing jQuery and making a few adjustments to your HTML should do the trick.

To start, enhance your buttons by giving them a unique attribute like data-id:

<button type="button" class="btn btn-primary btn-xs gridbtn" **data-id="btn1"** data-toggle="modal" data-target="#myModal">number</button>

Next, incorporate an input field into your modal window:

<input type="hidden" id="btnId" value="">

Whenever a button is clicked, ensure that the input field within the modal window captures the corresponding data-id value:

$('button').click(function() {
    $('.modal #btnId').val($(this).attr('data-id'));
});

This establishes a connection between the button opening the modal window and the window itself.

For changing the button color when a checkbox is checked, implement this jQuery code:

$('.checkbox').change(function() {
        if($(this).is(":checked")) {
            $('button[data-id='+$('#btnId').val()+']').css('color','red');
        }       
    });

Feel free to test out the demonstration here: http://jsfiddle.net/Lpdx3k83/

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

Replacing text in the main navigation bar with sIFR

Could this menu layout be improved? <div class="navigation"> <ul id="nav-menu"> <li class="active"> <div class="sifr-r active"><a href="#" title="home" class="top-link"><span class="blue-small">01.</span& ...

Alignment of menu blocks

I'm struggling to line up all the menu items at the bottom - products, activity feed, and learn store should be on the same row, with test below products. Currently, products is being pushed up and text is aligning to the right of it. Despite trying ...

Interactive HTML Table in PHP Email

I am curious to know if it is possible to include a user-defined function in PHP Mail. $to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ceabb6afa3bea2ab8eabb6afa3bea2abe0ada1a3">[email protected]</a>"; $mess ...

JavaScript is restricted from being accessed beyond the confines of the ui-view element

After coming across a problem similar to one previously dismissed on stack overflow, I decided to tackle it head-on. You can find the issue and attempted solutions at this link: Previous Problem and Solutions The full project solution is available on Gith ...

Tips for retrieving a variable from a $.getJSON function

My question is similar to this one: How can I return a variable from a $.getJSON function I have come across several duplicates on Stack Overflow, but none of them provided a satisfactory answer. I understand that $.getJSON runs asynchronously, and I hav ...

JSX/CSS: the text on the button is positioned outside of the button in Chrome browser

As I work on styling a React component using CSS, I noticed that I'm getting different results in Chrome and Firefox: Firefox (which is the desired behavior for both): https://i.sstatic.net/Q0LSD.png Chrome: https://i.sstatic.net/s2MWJ.png While I& ...

Expanding the blank area on the right margin of the page

Recently, I took a responsive website template and converted it into an ASP.NET MVC app. However, I've encountered some peculiar behavior when resizing the browser window. As the width of the window decreases below 986 pixels, a mysterious white "spac ...

Closing Note in Drupal

Is there a way to adjust the footer message in Drupal without logging into the dashboard? I've checked all the files in cPanel, but I can't seem to locate the actual HTML for the website. I am only able to customize the body content, not the fo ...

Tips for making a div with a single triangular side using Reactjs

Hey there, I'm looking to design a header similar to the one shown in this image. Can someone provide guidance on how I can achieve this UI using React.js? https://i.sstatic.net/zmW5x.jpg ...

Looking to establish a minimum height for a webpage

I am working on creating a webpage with three distinct sections: A fixed height header A fluid main section A fixed height footer My goal is to ensure that the page has a minimum height so that the bottom of the footer aligns with the bottom of the wind ...

HTML4 section tag failing to generate columns in proper alignment

Currently, I am organizing a list of movies by decade using the article and section elements. An issue has arisen: the alignment between the second and third rows is perfect while the first row seems slightly off-kilter. Below is the code snippet in questi ...

The content is unclipped with a border-radius and hidden overflow

As I work on incorporating stylistic text inside rounded divs, I encounter a challenge where the text touches the top of the container. While I have successfully managed to customize various content elements such as nested divs and background images, this ...

The functionality of jQuery .Show() may be affected when a negative margin is present in the

Check out this demo on Codepen that showcases the issue: http://codepen.io/theclarkofben/pen/xKhsd The .Show() effect isn't working as expected due to the negative margin applied to the div. Can someone shed light on why this behavior is occurring? ...

Issue with Jcrop not functioning properly in IE8

Having trouble with jCrop. It works fine in other browsers but not in IE8. Can't seem to figure out what the issue is. Wondering if it's related to image data or the size preventing the crop. Any assistance would be appreciated! <script typ ...

What is the best way to use identical styles for 2 different classes at separate breakpoints?

Is it possible to apply a chunk of (S)CSS to two different elements in two different breakpoints to avoid redundancy? I am using Bootstrap 4.6. <div class="one"> <div class="content">Something</div> </div> & ...

What is the best way to attach every sibling element to its adjacent sibling using jQuery?

I've been working with divs in Wordpress, where each div contains a ul element. <div class="list-item"> <div class="elimore_trim"> Lorem ipsum </div> <ul class="hyrra-forrad-size-list"> <li>Rent 1< ...

MVC3: Easily browse through tables by accessing details directly from the details view, eliminating the need to click on

I am currently working on an Index view where a table displays a list of items, each with a link to show its details in another partialview loaded through Ajax. Users have expressed interest in being able to easily navigate between "Next Item" and "Previo ...

What are the steps to display the entire image instead of a cropped version?

Currently in the process of constructing a website using HTML/CSS/Bootstrap/Js. I have encountered an issue while attempting to overlay a jumbotron on a container with a background image utilizing z-index. Unfortunately, the background image I am using k ...

What is the best way to handle JSON data from an HTTP request using Vue and an HTML script?

Looking for guidance on how to process the json data from this link to display attributes such as latitude, longitude, speed, etc. using vue and html? Json-content: { "64dda53cc503629cedb5f8c8102708ed": { "Test": { "lat": 50, "lon": 10 ...

PyQt TreeView scrollbar obstructing the header

I've been experimenting with the QTreeView widget (instead of QListView) in order to have a horizontal header. Additionally, I wanted to use stylesheets to customize the colors and appearance of the header and scrollbars. However, there is an issue w ...