What could be causing the jQuery to not trigger events for the HTML I am trying to push?

Kindly adhere to these instructions:

  • Execute the code snippet below
  • Tap on click here
  • Select the draw button
  • Press on the start again link
  • Click on click here, Notice that nothing occurs.

What is causing this issue? And how can it be resolved?

set_container();
$("body").one('click', '#one_to_many', function () {
    $(this).html('<form action="demo_form.asp">\
                        <input type="checkbox" name="graph" value="like" checked> one<br>\
                        <input type="checkbox" name="graph" value="comment" checked> two<br>\
                        <input type="checkbox" name="graph" value="friend" checked> three<br>\
                        <input class="graph_btn" type="button" value="draw">\
                    </form>');
});


function set_container() {
    $(".set_value").html('<div id = "one_to_many" class="draw_graph col-md-8 col-md-offset-2 text-center" style="margin-bottom: 25px;">\
                            click here\
                            </div>');
}


$("body").on('click', '.graph_btn', function (e) {
    $(this).attr('disabled', 'disabled');
    $(this).css({"cursor": "wait", "opacity": ".5"});
    $(this).after('<a onclick="set_container();">start again</a>');
});
    .draw_graph{
        border: 4px double #ccc;
        padding: 20px;
        font-size: 40px;
        color: #777;
    }
    .draw_graph:hover {
        background-color: #f9f9f9;
        cursor: pointer;
    }
    .draw_graph span{
        font-size: 13px !important;
        display: inline-block;
    }

    .draw_graph form{
        margin: 0 auto;
        font-size: 20px;
        line-height: 2;
        display: table;
        text-align: left;
    }
    .draw_graph input[type=button]{
        margin-top: 10px;
    }
    .draw_graph a {
        font-size: 15px;
        display: block;
        margin-top: 10px;
        color: #1e6be5;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container thumbnail thumbnail-post col-sm-12 set_value" style="padding: 30px;">

    </div>

Answer №1

Eliminate the one use of on and apply .stopPropagation() to avoid triggering parent clicks. See the code snippet below for implementation:

set_container();
$("body").on('click', '#one_to_many', function () {
    $(this).html('<form action="demo_form.asp">\
                        <input type="checkbox" name="graph" value="like" checked> one<br>\
                        <input type="checkbox" name="graph" value="comment" checked> two<br>\
                        <input type="checkbox" name="graph" value="friend" checked> three<br>\
                        <input class="graph_btn" type="button" value="draw">\
                    </form>');
  $("#one_to_many").unbind("click").bind("click");
});


function set_container() {
    $(".set_value").html('<div id = "one_to_many" class="draw_graph col-md-8 col-md-offset-2 text-center" style="margin-bottom: 25px;">\
                            click here\
                            </div>');
}


$("body").on('click', '.graph_btn', function (e) {
    e.stopPropagation();
    $(this).attr('disabled', 'disabled');
    $(this).css({"cursor": "wait", "opacity": ".5"});
    $(this).after('<a onclick="set_container();">start again</a>');
});

$("body").on('click',"form",function(e){
e.stopPropagation();
})
.draw_graph{
        border: 4px double #ccc;
        padding: 20px;
        font-size: 40px;
        color: #777;
    }
    .draw_graph:hover {
        background-color: #f9f9f9;
        cursor: pointer;
    }
    .draw_graph span{
        font-size: 13px !important;
        display: inline-block;
    }

    .draw_graph form{
        margin: 0 auto;
        font-size: 20px;
        line-height: 2;
        display: table;
        text-align: left;
    }
    .draw_graph input[type=button]{
        margin-top: 10px;
    }
    .draw_graph a {
        font-size: 15px;
        display: block;
        margin-top: 10px;
        color: #1e6be5;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container thumbnail thumbnail-post col-sm-12 set_value" style="padding: 30px;">

    </div>

Answer №2

Essentially, the issue was caused by clicking on a nested child element within a parent element.

To resolve this problem, I made some modifications to the code and inserted e.stopPropagation(); in the click event handler of the child element to prevent the parent's click event from firing.

Here are the key changes:

1 - Replaced $("body") with $(document)

2 - Included alert() for debugging purposes (can be removed later)

3 - Updated all instances of #one_to_many to .one_to_many

set_container();
$(document).on('click', '.one_to_many', function () {
    
    $(this).html('<form action="demo_form.asp">\
                        <input type="checkbox" name="graph" value="like" checked> one<br>\
                        <input type="checkbox" name="graph" value="comment" checked> two<br>\
                        <input type="checkbox" name="graph" value="friend" checked> three<br>\
                        <input class="graph_btn" type="button" value="draw">\
                    </form>');
$(".one_to_many").unbind("click").bind("click");

});
...

// The rest of the JavaScript code remains unchanged
// CSS styles for .draw_graph class
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container thumbnail thumbnail-post col-sm-12 set_value" style="padding: 30px;">

    </div>

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

The Chrome browser is experiencing issues with Bootstrap dropdowns that require a selection when the value is

Currently, I am facing an issue with a dropdown menu where users have to select a country from the list. The problem is that the code works correctly in Firefox (the second option, which has an empty value, does not fulfill the required step), but Chrome o ...

Unable to set or select options using JavaScriptExecutor in C# Selenium

Below is a snippet of HTML code: <div class="k-list-scroller" unselectable="on" style="height: auto;"> <ul unselectable="on" class="k-list k-reset" tabindex="-1" aria-hidden="true" id="AdmittedFromId_listbox" aria-live="off" data-role="static ...

The ts-node encountered an issue with the file extension in this message: "TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension

When using ts-node, I encountered the following error: $ ts-node index.ts TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/projects/node-hddds8/index.ts I attempted to remove "type": "module& ...

Loading data dynamically in the Highcharts ng library allows for real-time updates to the

I'm currently working on integrating highcharts ng into my Angular project, but I'm encountering issues with data not populating. It seems like there might be a problem related to the loading of the DOM and the function call. Here's my HTML ...

What is the best way to detect modifications to scope variables within a directive?

Here are some instructions for HTML: <dropdown placeholder='' list='sizeWeightPriceArr' selected='selectedProductSize' property='size' value='size' style='width:60px;'></dropdown> Th ...

The operation state.concat cannot be performed as it is meant for arrays and not for type 'ITask'

Trying to incorporate an array into my store is causing issues with the following error popping up at tasks: payload.payload ? [ ...state, payload.payload ] : []: Error:(22, 35) TS2461: Type 'ITask' is not an array type. Any suggestions on how t ...

Dropping and dragging in the Dojo for the nested lists

Within my HTML code, I am using the Dojo drag and drop feature to sort attributes and move them to another section. However, I am having trouble figuring out how to sort the sections themselves. Here is the structure that I have created: <ul accept=" ...

Retrieve the parent object within a constructor function

Is there a way to access the parent object when calling a function contained inside that object as a constructor without explicitly referring to it? Take a look at this scenario: var customers = { // Number of customers count: 0, // Naturally ...

Utilizing Selenium to Click and Drag on the Browser Window in Order to Select Text on the Website

I am attempting to mimic the action of highlighting text on the screen by moving the cursor to a specific element and clicking and dragging. However, my current code does not seem to be replicating this behavior as expected. Despite defining the element, ...

Issue with Vuetifyjs theme variable failing to function properly in version 1.0.0

Check out the step-by-step instructions provided in https://vuetifyjs.com/en/style/theme. I successfully changed the theme using the code below with vuetifyjs version 0.13.0. However, after updating to vuetifyjs 1.0.5, the font still displays correctly bu ...

Collecting information from JSON files

Within the cells of my calendar are placeholders for events, dates, participants, and descriptions. Now, I am looking to populate these placeholders with data previously stored using localStorage. Unfortunately, my current code is not achieving this. How ...

After a postback triggered by a different update panel, the item that was initially added to the dropdown menu using

Why do I encounter an issue with two update panels both set to conditional mode? In the first update panel, I have two dropdowns where selecting an item in the first dropdown triggers the addition of an item in the second dropdown via JavaScript. The sec ...

Vuejs: Users can still access routes even after the token has been deleted

Upon logging out of my application, I have encountered a peculiar issue. Certain inner links, such as those within a user's panel, remain accessible even after I have logged out and deleted a token. However, other links are not. Any suggestions on how ...

Is it possible to import data into a script?

When working with Angular, I am attempting to: $scope.data = "<script> alert('hi'); </script>"; Unfortunately, this approach does not seem to be effective. I also experimented with adding ng-bind-html but did not achieve any success ...

Links for pagination become unresponsive after moving past the initial page

I'm currently troubleshooting a pagination script and encountering issues. When I try to navigate through the pagination links such as [1], [2], [3], [4], or [5], it doesn't function properly. It only displays the first page, and clicking on subs ...

When using i18next interpolation in React components, the displayed output may show as [object Object]

In my React application, I am utilizing the next-i18next package. I want to include a React component within my interpolation: import React from 'react'; import { useTranslation } from 'next-i18next'; import { serverSideTranslations } f ...

Checking if the current value matches the previous value retrieved from a JSON file using JavaScript

Uncertain about how to phrase the question title or the correct way to ask for assistance with this issue. The objective is to extract data from an external Json file consisting of approximately 700 entries. When iterating through these data items, such a ...

Generate an array of arrays containing objects using different variable names

Here is the issue at hand: const data : [ {labelSlug: 'cola', category: 'catering', subCategory: 'drinks', provider: 'coca cola'}, {labelSlug: 'cola', category: 'catering', subCategory: 'drin ...

Stop Bootstrap IE menu from closing when scrollbar is clicked

When using IE, the dropdown menu closes when clicking on the scrollbar. However, it functions properly when scrolling with the mouse wheel. To see the issue in action and potentially offer a solution, you can visit this Codeply link: I'm seeking sug ...

Dynamic class/interface in Typescript (using Angular)

Is there a way to achieve intellisense for an object created with a dynamic class by passing parameters? Here is the code snippet: Main: let ita: any = new DynamicClass('ITA'); let deu: any = new DynamicClass('DEU'); The DynamicClass ...