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

I encountered an error while using the router: TypeError: Cannot read property 'use' of undefined

Hello everyone, I am new to node.js and seeking help from experts. I am currently working on a code for user synchronization using node.js + AWS Cognito + Facebook Login. I followed an example from this link. Everything was going smoothly until I reached ...

implement an angular directive to apply a CSS element

I am utilizing AngularJS and ng-repeat to populate a dynamic list of studies. This list has the capability to toggle into child elements of each item, creating an accordion-style toggle list that can go up to three levels deep for each list item. I am curr ...

Retrieve values from the query string (specifically from table rows and cells) for each individual line and display them in

i have some code, see: <script> $$.ready(function() { // Profile Dialog $( "#user-dialog" ).dialog({ autoOpen: false, modal: true, width: 400, open: function(){ $(this).parent().css('overflow', 'visible') ...

Exploring the possibility of utilizing the talks.js library to develop a chat feature within a React application

I'm currently working on integrating the talks.js library to set up a chat feature in my React project. I've followed all the instructions provided at , but unfortunately, it's not functioning as expected. I'm not quite sure what I migh ...

Asynchronous NestJs HTTP service request

Is there a way to implement Async/Await on the HttpService in NestJs? The code snippet below does not seem to be functioning as expected: async create(data) { return await this.httpService.post(url, data); } ...

Verifying the presence of a cookie when the page loads

My goal is to have the browser initially check for a cookie named "yes." If this cookie exists, I would like to show a message. If not, I want to display the following: <input type="button" id='approve' value="approve" onclick="a()"/> &l ...

What could be causing my page's wrapper to shrink upon logging in?

After logging out, the background of my page wrapper expands to cover 100% of the page. However, once you log back in, it shrinks and adjusts to the width of the member bar... TO TEST USER ACCOUNT BELOW: USERNAME: TEST PASSWORD: TEST123 HTML FOR LOGGED ...

Learning how to invoke a JavaScript function from a Ruby on Rails layout

In the file app/views/download.js.erb, I have defined a javascript function named timeout(). This function continuously polls a specific location on the server to check if a file is ready for download. I am currently running this function as a background ...

Send back a JsonResult containing a collection of objects from an MVC controller

In my MVC controller, I have a straightforward method: [HttpPost] public JsonResult GetAreasForCompany(int companyId) { var areas = context.Areas.Where(x => x.Company.CompanyId == companyId).ToList(); return Json(areas); } Here is the structure ...

Updating Angular view based on service parameter change

In-depth Inquiry I have a specific setup with a header view and a main view in my Angular application. The goal is to include a "back" button in the header that should only be visible based on the current page I'm viewing. Actions Taken In my app ...

Hover state remains persistent even after modal window is activated in outouchend

One of the buttons on my website has a hover effect that changes its opacity. This button is used to share information on Facebook. It's a simple feature to implement. Here is the CSS code: .social_vk, .social_fb { height: 38px; obj ...

Deciphering JSON information extracted from a document

I am currently working on a Node JS project where I need to read a file containing an array of JSON objects and display it in a table. My goal is to parse the JSON data from the array. Below is a sample of the JSON data: [{"name":"Ken", "Age":"25"},{"name" ...

Limiting the jQuery UI Datepicker to only allow past dates: How to make it happen?

I have implemented a jQuery UI Datepicker that restricts selection to only Sundays. However, I want to further enhance this by preventing users from selecting any dates in the future starting from today. Below is the current code snippet I am using for th ...

"Exploring the Dynamic Duo: Ajax_JQUERY and the Power of

I am a beginner in Laravel and I'm looking to include edit and show buttons in the Controller using my controller below <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class LiveSearch extends Contr ...

Utilizing JQuery Mobile to handle multiple forms on a single page and submitting each form uniquely by its ID using JQuery Post

After experimenting with assigning the same form ID to all forms on the page and also giving each form individual IDs with unique.submit functions, I encountered an issue where only the first form would work while the rest would redirect me back to the hom ...

What is the purpose of using the variable "header_row || 1" in App Script?

Recently, I stumbled upon a spreadsheet that contains app script for gathering keys of data requested through doGet. In the code, there is a line that reads like this: var headRow = e.parameter.header_row || 1; What exactly does this line mean? I searc ...

Access the value of localStorage when the body has finished loading or when the document is fully

Utilizing jQuery UI 1.12.1 alongside jQuery 3.1.1, I have implemented a function to save the state of two tabs in localStorage under currentIdx: $("#tabs").tabs({ active: localStorage.getItem("currentIdx"), activate: function(event, ui) { localSto ...

Unsure why my React component isn't triggering a re-render?

I encountered an issue when trying to update my component based on a state change. When I update the state outside of an HTTP call, the component updates correctly. However, when I try to do the same inside an HTTP get call, the state is updated but the ...

Displaying Image Preview in Angular 2 After Uploading to Firebase Storage

At the moment, I am facing an issue where the uploaded image is not being displayed after the uploadTask is successful. This problem arises due to the asynchronous loading nature of the process, causing the view to attempt to display the image before the u ...

Markdown boasts of a sturdy partially-horizontal line

Is there a way to create a partially colored line in Markdown? I attempted using the following code: <hr style="border:0.3px solid green; width:40%"> </hr> However, instead of a partial green line, I am seeing a full gray line. Any idea on w ...