Trouble arises when attempting to bind a JavaScript event with an innerHTML DOM element

I am currently dealing with a complex issue on how to bind a JavaScript event to an innerHTML DOM element. The scenario involves having a div with an input checkbox inside it, along with some pre-existing JavaScript event bound to that checkbox. Additionally, there is another div containing some text content. Now, through JavaScript, the goal is to create a new div where the content will be a combination of the existing two divs, while maintaining the JavaScript event for the checkbox.

While I have managed to achieve most of this task successfully, there's one challenge remaining. When transferring the checkbox from the previous div to the newly created div using innerHTML, the JavaScript event does not carry over.

The current HTML structure looks like this:

<div id="text_holder">
"Lubricant"
<input type="checkbox" id="Lubricantc" class="check_class">
</div>

<div id="text_holder2">
SKF,FAG
</div>

"text_holder" and "text_holder2" are the names of the two existing div elements.

The JavaScript code responsible for creating a new div, combining data from the previous divs, and placing it in the new div is as follows:

var previous_ig_content=document.getElementById("text_holder");
var previous_brand_content=document.getElementById("text_holder2");
var child_div=document.createElement('div');
child_div.id=ig_id+"div";
child_div.innerHTML=previous_ig_content.innerHTML+previous_brand_content.innerHTML;

I have conducted extensive research to solve this issue but haven't found a proper solution yet. Any assistance in resolving this matter would be greatly appreciated. Thank you in advance!

Below is my complete JavaScript code:

 <!-- Your JavaScript code goes here -->

Answer №1

Give this a try! I've made a slight adjustment by replacing the checkbox with a button that triggers upon clicking. Feel free to switch it back to a checkbox if needed.

function checkFunc(){
    var previous_ig_content=document.getElementById("text_holder").innerHTML;
  var previous_brand_content=document.getElementById("text_holder2").innerHTML;
  var childDiv = document.createElement('div');
  childDiv.id="newDiv";
 childDiv.onclick =alertMess;
 childDiv.style.backgroundColor = "red";
 childDiv.style.cursor = "pointer";   childDiv.innerHTML=previous_ig_content+previous_brand_content;
  document.getElementsByTagName('body')[0].appendChild(childDiv);
}

function alertMess(){
  alert("oh! you clicked the generated div");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text_holder">
"Lubricant"
<!-- <input type="checkbox" id="Lubricantc" class="check_class" ></input> -->
<button onclick="checkFunc()">Click me</button>
</div>
<div id="text_holder2">
SKF,FAG
</div>

Answer №2

When using native JavaScript, you can utilize the innerHTML method or the cloneNode function. However, it's important to note that they only clone the inline listeners and not those added with the addEventListener method. See the demonstration below:

// checkbox listener
document.querySelectorAll('input[type=checkbox]')[0].addEventListener('click', function() {
  console.log("clicked");
});

// clone and append
document.body.appendChild(document.querySelectorAll('.wrapper')[0].cloneNode(true));

// inline listener
function inline() {
  console.log("inline");
}
.wrapper {
  padding: 10px;
  border: 1px solid red;
  display: inline-block;
  vertical-align: middle;
}
<div class="wrapper">
  <span>Yes / No</span>
  <input type="checkbox" onclick="inline()" />
</div>

Solution

If JQuery is used, there is a solution available - the clone method. By specifying true, event handlers are also copied! Explore the demo below:

$(function() {
  // checkbox listener
  $('input[type=checkbox]').on('click', function() {
    console.log("clicked");
  });
  // clone and append
  $('body').append($('.wrapper').clone(true));
});

// inline listener
function inline() {
  console.log("inline");
}
.wrapper {
  padding: 10px;
  border: 1px solid red;
  display: inline-block;
  vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <span>Yes / No</span>
  <input type="checkbox" onclick="inline()" />
</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

Unraveling the mysteries of deciphering extended JSON information

Issue with Data Interpretation I am facing a challenge in my project that is more related to understanding and interpreting data rather than writing code. The project involves using a NoSQL database, specifically MongoDB, to store information sampled from ...

Navigating between divs with a 100% height using up and down movements

I am working on a website that is structured into different sections using divs with shared classes but unique IDs. Each div is set to take up 100% of the viewport height. To navigate between these sections, I want to provide Up/Down arrow buttons for user ...

Extracting individual elements from an array with Node.js or JavaScript

let array1= [ "home/work/data.jpg", "home/work/abc.jpg", "home/work/doc/animal.pdf", "home/work/doc/fish_pdf.pdf" ]; array1= array1.map((data)=>{ return data.slice(2,data.length).join("/"); }); console.log(array1); i am trying to modify my array by re ...

Why isn't Bootstrap validation functioning properly in my Modal?

I am attempting to implement client-side validation using bootstrap, as outlined here: https://getbootstrap.com/docs/4.0/components/forms/#custom-styles The challenge I'm facing is that my form is within a modal. When I click the submit button, nothi ...

What methods can I utilize to persuade Internet Explorer to directly show the content of application/json instead of prompting to download it?

While troubleshooting jQuery applications that utilize AJAX, I often find myself needing to inspect the JSON data returned by the service in the browser. To do this, I simply input the URL for the JSON data into the address bar. One advantage of using ASP ...

Zebra Calendar Alignment Problem

Currently working on an asp.net app and utilizing the Jquery Zebra DatePicker. Encountering an issue where when opening the form in a Jquery dialog, the calendar appears at the bottom of the page instead of within the dialog. A similar problem was discus ...

Utilizing 'this' in jQuery: Image swapping with thumbnails, Twitter Bootstrap framework

Is it possible for jQuery's 'this' to simplify my code? You can view the full code here. Thank you for any help or suggestions. Here is the jQuery code: /* Ref: http://api.jquery.com/hover/ Calling $( selector ).hover( handlerIn, handler ...

Tips for ensuring a static html element remains visible at the bottom of the screen even when the soft keyboard is opened in iOS Safari

Within a webpage, there is an input field and a fixed div positioned at the bottom of the window using CSS properties such as position:fixed; and bottom:0;. To better illustrate this setup, I have created a Codepen demo which can be viewed here: https://c ...

Recursive sorting and parsing of JSON data with multiple levels

I'm new to using recursion in JavaScript and need some guidance to understand it better. I have a JSON data structure with multiple levels of nested "subcategories". const STORE_CATEGORIES = [{ "Id":"1", "Name":"One Parent", ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

Tips for transferring an array from a php page to a javascript page

In my PHP code, I have an array structured like this: 1) <body onload="addMarkers(<?php print_r($myArray) ?>)"> 2) <body onload="addMarkers(<?php echo json_encode($myArray) ?>)"> Unfortunately, these attempts were unsuccessful. U ...

I'm noticing that the top border for my span is smaller than the bottom one. What could

I am struggling to create an arrangement of three triangles in a line, with the first and third pointing up and the middle one pointing down. The upper triangle seems to be too small - any ideas on how to adjust this? Is there another way to achieve this ...

Looking for a straightforward way to incorporate a "Read more" and "Show Less" functionality into a Wordpress site using Javascript?

As a last resort, I am seeking a quick and simple fix. I have been experimenting with Javascript to implement a 'Read more...' & '... Read Less' feature on six different sections of a single page. The goal is to display only the fi ...

What methods can I use to pass an argument from an HTML file to jQuery?

I need to retrieve the value 7 from the HTML file <button id="buttonseven" onclick="buttonClick(7)">7</button> How can I capture this value using jQuery? $(document).ready(function(){ $('#buttonseven').click( ...

Tips for integrating tooltips in a dynamic highcharts chart

This image shows the desired final output View Highcharts here and I am looking to merge the date and stock value in a single tooltip, how can this be achieved? highcharts ...

What is the best method for submitting information using AJAX and jQuery?

Here is the HTML code in question: <script src='https://code.jquery.com/jquery-1.12.4.min.js'></script> <p>1</p> <!-- this content gets loaded with <?php echo $item->id; ?> --> <a id='delBtn1' ...

Sharing data between controllers within an MVC architecture in JavaScript

I'm currently working on an app using Express and Node. Within my routes, I have '/new-poll' and '/poll-create' //The route poll-create allows users to create a new poll app.route('/poll-create') .get(functi ...

Steps for Creating an Animation Tool based on the Prototype:

One question that recently came up was: What is the best approach to tackling this issue? Developing a tool that enables designers to customize animations. To make this process easier, it is essential to create an AnimationSequence using JavaScript that ca ...

Click on the button to sort Angular data

Greetings! I am a newcomer trying to grasp the concepts of angularjs/typescript. I have compiled an array of fruits, displayed in an unordered list. My goal is to arrange them in descending order and implement a reverse search function to display the item ...

Notifying with Socket.IO in Node.js

Hey there, I'm currently working on implementing a notification system but have hit a roadblock. I've sent an invitation to a user to join the club. socket.on("notify", async (message) => { // invite the user John Doe io.to('socke ...