Transferring checkbox data to Bootstrap modals and dynamically summoning specific div modals using their unique identifiers

I have been trying to populate the checkbox values into corresponding modal divs based on button clicks, but I am facing difficulties in achieving it.

Desired outcome: The buttons should trigger the display of selected checkbox values in their respective modal divs.

Thank you for your assistance.

$(document).ready(function(){

var favorite = [];
    $.each($("input[name='sport']:checked"), function() {
      favorite.push($(this).val());
    });

$("button1").click(function() {
$("#myModal").modal('show').on('shown.bs.modal', function() {
      $("#checkid").html("I play these games " +"<br>" + favorite.join("<br>"));
    }); 
});
$("button2").click(function() {
 $("#myModal2").modal('show').on('shown.bs.modal', function() {
      $("#checkid").html("I dont Play these games " +"<br>" + favorite.join("<br>"));
    }); 
});

});
<div id="myModal1" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
         These are the games that I usually play and excel at:<br>
        <p id="checkid"></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<div id="myModal2" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        These are the games that I don't usually play but would like to try:<br>
        <p id="checkid"></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<form>
  <h3>Select your favorite sports:</h3>
  <label>
    <input type="checkbox" value="football" name="sport"> Football</label>
  <label>
    <input type="checkbox" ; value="baseball" name="sport"> Baseball</label>
  <label>
    <input type="checkbox" value="cricket" name="sport"> Cricket</label>
  <label>
    <input type="checkbox" value="boxing" name="sport"> Boxing</label>
  <label>
    <input type="checkbox" value="racing" name="sport"> Racing</label>
  <label>
    <input type="checkbox" value="swimming" name="sport"> Swimming</label>
  <br>
  <button type="button">Get Values</button>
</form>
<button  id = "button1" type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" >I play these games</button>
  <button  id = "button2" type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal2">I dont play these games</button>

Answer №1

It seems that you may have overlooked some instances where the # character is missing. Here is a corrected version for you to try:

$(document).ready(function(){
    $("#button1").click(function() {
        var p=$("#myModal1 #checkid");
        $(p).html("I enjoy playing these games ");
        $.each($("input[name='sport']:checked"), function() {
            $(p).html($(p).html() + '<br>' + $(this).val());
        });      
    }); 
    $("#button2").click(function() {
        var p=$("#myModal2 #checkid");
        $(p).html("I do not play these games ");
        $.each($("input[name='sport']:checked"), function() {
            $(p).html($(p).html() + '<br>' + $(this).val());
        }); 
    });
});

For the HTML section, update

<button  id = "button1" type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" >I play these games</button>

to

<button  id = "button1" type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal1" >I play these games</button>

Answer №2

To start, make sure to update your selector: $('#button1') instead of $('button1') and then relocate the code snippet

var selectedSports = [];
$.each($("input[name='sport']:checked"), function() {
  selectedSports.push($(this).val());
});

Ensure that this code is placed inside your click function to prevent your selected sports array from loading only once when the page finishes loading.

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

Having issues with the environmental value not functioning properly within the .js file for Next.js

Currently, I am in the process of testing an app that features a widget which relies on an API key within a script. This script needs to be placed within my <head> tags. My .js file is located in my public folder and is being imported into my layout. ...

The issue with NGX-Bootstrap/Angular Pagination arises when attempting to adjust the maxSize input while the screen view (width) is being altered

Currently, I am utilizing the Pagination component from Valor Software (click here to access). I am interested in adjusting the maxSize input dynamically based on changes in screen width. For reference, please see this example: Click to view example. It ...

What is the purpose of wrapping my EventEmitter's on function when I pass/expose it?

My software interacts with various devices using different methods like serial (such as USB CDC / Virtual COM port) and TCP (like telnet). To simplify the process, I have created a higher-level interface to abstract this functionality. This way, other sect ...

Looking to conceal a JavaScript file or minimize it from the web browser following production build in React

Upon executing the npm run build command using the script provided in my React App's package.json file, "scripts": { "start": "react-scripts start", "build": "set 'GENERATE_SOURCEMAP=false&apos ...

Utilizing Promise and setTimeout in a generator function to develop an asynchronous generator: A comprehensive guide

I am currently working on creating a generator function that produces an async generator. This Generator will yield a deferred value at each time, using promises. The values and their respective delays (in milliseconds) are sourced from two separate arrays ...

Expanding the background further than the parent's width using HTML and CSS

I am looking to extend the background color or image to mimic the appearance of the example at the bottom in this jsfiddle Same code but showcased here: Example1: <div class="fixed_width"> <div class="header">Header</div> <div ...

Break the line after every space in words within an element

I have a table/grid view with two words in the <td> like "C2 Sunday". I need a line break after C2 so that it appears as: C2 Sunday Is there a way to achieve this? Please assist me with this issue. Currently, it is showing as "C2 Sunday" and I wou ...

Jquery not populating dynamic dropdown with Onchange event

When using Jquery Ajax to populate the dynamic dropdown in my HTML table with JSTL-foreach iteration, I encountered an issue where it only works for the first row and not for the subsequent rows. $(document).ready(function() { $('#roleId').o ...

Strategies for selecting glyphs in SVG fonts based on their Unicode properties

My goal is to extract specific characters from SVG fonts created for music engraving. Music fonts typically include a large collection of characters (> 3500), but I only require a small subset of them for caching glyphs in compressed form to ensure quic ...

When the nav-element is clicked, it will load the new content/file.php into the div with the id of "include."

Seeking the most efficient method to load content from a php file into a designated div on my webpage, prioritizing speed, minimal performance requirements, and ease of implementation. Unsure whether it's preferable to utilize php or javascript for t ...

The inclusion of the <div> tag disrupts the functionality of the Material UI Grid

While attempting to enclose my element within a <div> that is nested inside the <Grid>, I realized that this was causing the <Grid> layout to break! Surprisingly, when I tried the same approach with Bootstrap grid system, this issue did n ...

When placing the script URL with a pound sign into the DOM, it gets truncated

When I receive URLs for trackers from an external resource, they often contain a # symbol which causes the URL to be cut off after the pound sign when trying to execute/load it in the DOM. Unfortunately, these URLs are provided by a 3rd party and I have no ...

Achieving dynamic placement of Vue components

There are numerous panels (products) displayed on a page in multiple rows and columns. Using Vue 2 with components for the panels, I aim to show details of each panel below its respective row upon clicking, similar to Google image search. https://i.stack. ...

The tooltip being displayed is plain and lacks any design elements

When I hover over my a element, only a simple tooltip appears without any styling, unlike what is shown in the Bootstrap documentation. (I am creating the a element using JavaScript) HTML <!DOCTYPE html> <html lang="en"> <head> ...

Remove a row from a table and implement a Bootstrap modal for confirmation

I am currently working on a task in my CodeIgniter framework project where I need to delete a row from a table of users. The desired functionality is to click the delete button, have a modal window appear asking the user for confirmation to delete the rec ...

PHP unable to retrieve ID from URL

Is there a way to extract an id from the URL when clicking a button for the purpose of deleting an item from a session? I have tried using $_GET but it doesn't seem to work. <form action="Shop.php?id= <?php echo $values["ProductCode"]; ?>" m ...

Creating an outlined effect on a transparent image in a canvas: step-by-step guide

Currently, I am working on creating transparent images using canvas in HTML5 and I would like to incorporate borders into them. The issue I'm facing is that the "Stroke" property does not consider the transparency of the image and applies it as if it ...

Incorporating a rigged and animated asset into a preexisting scene using Three.js

Currently, I'm developing a browser app similar to Tamagotchi using three.js. However, I've hit a roadblock while trying to implement a hand that can pet the avatar when clicked. The Hand is a rigged Blender model with two animations: idle and p ...

Ways to verify the functionality of a webpage once it has been loaded on my local machine's browser

I manage a website that is currently hosted on a server and being used by thousands of visitors. The site is created using Java and soy template technology. I am looking to test the frontend rendering and JavaScript files. Can this be done directly from my ...

Setting up initial values for a JSON array in an AJAX function upon the document being fully loaded

I am currently developing an Ajax function that passes values from an array. My goal is to simplify the process of handling various translations by creating a JSON file containing all the required translations and then making it available to my main Ajax f ...