Using jQuery to trigger a Bootstrap modal when a button is clicked

I've been attempting a simple task, but it appears to be unsuccessful. I'm trying to handle the click event of a button inside a bootstrap modal, and so far, nothing happens when clicking the button. My guess is that my jQuery selector for selecting the button inside the modal is incorrect.

The problem arose when using alert() with the modal. html:

<!-- Duel -->
<div class="modal fade" id="duel_pp" tabindex="-1" role="dialog" aria-labelledby="duel_pp">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="duel_pp_content">Duel</h4>
      </div>
      <div class="modal-body">
       <div id="userlist">
        <table>
          <thead>
            <th>Player</th>
            <th>Energy</th>
            <th>Country</th>
            <th>Region</th>
            <th>Duel</th>
          </thead>
          <tbody></tbody>
        </table>
      </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

script.js:

// DOM Ready =============================================================
$(document).ready(function() {
   $("#duel").click(function(){
        populateTable();
    });

})  
$(document).on("click", "#duel_pp #select_target", function(){
    //var id = $(this).closest("tr").find(".target_name").text();
    alert("hello world!");
});
// Functions =============================================================

// Fill table with data
function populateTable() {

    // Empty content string
    var tableContent = '';

    // jQuery AJAX call for JSON
    $.getJSON( '/modalRoutes/validTargets', function( data ) {
        // For each item in our JSON, add a table row and cells to the content string
       $.each(data, function(){
            tableContent += '<tr>';
            tableContent += '<td class=\'target_name\'>' + this.local.username + '</td>'; 
            tableContent += '<td>' + this.local.energy + '</td>';
            tableContent += '<td>' + this.local.country + '</td>';
            tableContent += '<td>' + this.local.region + '</td>';
            tableContent += '<td> <button type=\'button\' id=\'select_target\' class=\'btn btn-danger\'> Duel </button></td>';
            tableContent += '</tr>';
        });

        // Inject the whole content string into our existing HTML table
        $('#duel_pp #userlist table tbody').html(tableContent);
    });
};

I also tried adding click under $(document).ready but same thing.

$("#duel_pp #select_target").click(function(){
        alert('hello world')
});

Answer №1

Here is a suggestion that might help:

function populateTable() {

    // Using jQuery to make an AJAX call for JSON data
    $.getJSON( '/modalRoutes/validTargets', function( data ) {
        // Creating an empty string to store content
        var trContent = '';

        // Looping through each item in the JSON and adding table rows and cells to the content string
       $.each(data, function(){
            trContent += '<tr>';
            trContent += '<td class=\'target_name\'>' + this.local.username + '</td>'; 
            trContent += '<td>' + this.local.energy + '</td>';
            trContent += '<td>' + this.local.country + '</td>';
            trContent += '<td>' + this.local.region + '</td>';
            trContent += '<td> <button type=\'button\'  class=\'btn btn-danger select_target\'> Duel </button></td>';
            trContent += '</tr>';
        });

        // Adding the entire content string to our HTML table
        $('#duel_pp #userlist table tbody').append(trContent);

        var $trContent = $(trContent);

        // Setting up a click event for the 'select_target' button
        $trContent.find('.select_target').on('click', function(e){
            e.preventDefault();
            alert('hello world');
        });
    }
}

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

Ways to retrieve multiple pages using the .load function

Currently, I am constructing a manage account page using net core. The main issue I'm facing is loading content from various pages into a designated div when the user clicks on different items in the menu. How can I efficiently utilize this method wit ...

Fade in elements from an array using jQuery

Hey there, I'm currently facing an issue with using Javascript to process data within a function. Since I'm new to Javascript, I'm hoping for a simple explanation. My aim is to display each item from an array sequentially, with a fading in ...

"Adding jQuery functionality: displaying images in a popup on the same

Greetings to everyone here, it's my first time posting but I've been following some posts from time to time. So, hello all! I have a quick question that I haven't been able to find the answer for online. I'm dismantling a template to u ...

Problem with responsive design on iPhone

I'm currently working on developing a responsive chatbot using CSS Bootstrap. However, I've encountered an issue where the header and footer are not fixed when I open the app on an iPhone. The keyboard header is also moving up the screen, which s ...

My media queries refuse to cooperate until I add the magical "!important" declaration

Utilizing Bootstrap 4 along with a custom CSS file on my website. Within the CSS file, I have included some media queries at the bottom: @media (max-width: 575px) { .address .contact { text-align: center; } } /* Small devices (tablets, 768px and ...

Unable to retrieve JSON data from the given URL

Here is the JSON data I have: { "status": "ok", "count": 1, "data": { "6217895": { "clan": { "role_i18n": "Saha Komutanı", "clan_id": 16682, "role": "commander", ...

I have a query regarding the load function and JSON

Is it feasible to achieve something similar to this? $.ajax({ url: "test.php", success: function(json, json1){ //I wonder if I can have more than one parameter here? $m0 = []; $m0.push(parseFloat(json)); alert($m0); //display 750 $m1 ...

Failing to upload a file along with other form elements in Flask results in a 400 error

Encountering a 400 error when attempting to upload a file and send other form elements to Flask from HTML. Tried using AJAX, but it also gives me an error. Python: @app.route('/prod_diff_result', methods=['POST']) def prod_diff_result ...

Access the website by logging in with idhttp

I'm attempting to log in to a website using Delphi / Indy. Currently, I only have a button (used to send a password / username) that calls this procedure. procedure TForm5.Login(name: string; Pass: string); var UserID :string; Password :string; res : ...

Steps for incorporating a storyline into a CSS Chart

I'm attempting to introduce a horizontal line at a specific point using chartscss.org For instance, on the given chart utilizing Charts CSS below, I'm aiming to include a horizontal line at 15.5... Similar to the illustration shown. I've e ...

Turning On/Off Input According to Selection (Using jQuery)

<select name="region" class="selection" id="region"> <option value="choice">Choice</option> <option value="another">Another</option> </select> <input type="text" name="territory" class="textfield" id="territo ...

Creating a large and spacious modal in Angular using ngx-bootstrap

I need help with resizing the ngx-modal to cover a large area of the screen. Currently, I am trying to make it so that when something is clicked, the modal should overlay an 80% width grid on a full desktop screen. Despite my attempts at using .modal-xl an ...

There was an issue when trying to process the Javascript data structure with JSON.parse

Currently, I have the following data stored in a JavaScript variable: "{'Headings': [{'name': 'Behavior', 'majorTopic': 'N', 'vote': {'down': 1, 'up': 1}}, {'na ...

How to activate select only when specific options are chosen using jQuery

I am working on a form that has 1 select element disabled, with 4 options. I am looking to implement a jQuery function that will perform the following actions: If OPTION #1 is clicked, it should check if any other options are selected and reset them (eras ...

An effective guide on altering the style attribute of a div using jQuery

I am currently attempting to modify the style attributes of a div's style element using jQuery. Specifically, my goal is to adjust the position of the background image, which happens to be a sprite. Below is the main portion of my code, and you can al ...

What is the best way to customize the appearance of the elements in the hamburger menu within a Bootstrap navigation bar?

I have successfully implemented a responsive navbar using Bootstrap 4. When the screen size is large, there are 2 buttons displayed, and when it's small, a hamburger menu appears. [insert image description here][1][insert image description here][2] ...

The Jquery post function is malfunctioning

Below you will find the jquery code snippet: $(function () { $("#personCreate").click(function () { var person = getPerson(); // simple validation if (person == null) { aler ...

Mixing success and error states can lead to confusion when using jQuery and Express together

I've been struggling with a simple question that's been on my mind for quite some time. Despite my searches, I haven't found a similar query, so I apologize if it seems too basic or repetitive. The scenario involves an API route (Express-ba ...

PHP is causing disruptions to HTML

Every time PHP code is present in my file, the page appears blank and upon checking the source code, there are no tags visible on the page. However, once I remove the PHP code, the form displays correctly without any issues. <?php $title = $_POST[&apos ...

Check if the string contains any numerical characters

Is there a way to check if a string contains at least one numerical character without verifying if the entire string is a number? The current code works in the following situations: If there is a single integer, such as "43", it will display the correspon ...