Utilizing jQuery on the newly inserted <tr> element

I have created a jQuery code that includes 3 pre-existing rows with a text box to add more similar rows. The jQuery functions are initially applied to the first 3 hard-coded rows. I am looking to extend this functionality to dynamically added rows later on. How can I achieve this? Here is the code snippet:

$('input[type="checkbox"]').click(function() {
  $(this).next('label').toggleClass('checked', '');
});

$('.glyphicon.glyphicon-trash').click(function() {
  $(this).closest("tr").remove();
});

var i = 4;

$("input[type='text']").keypress(function(event) {
  if (event.which === 13) {
    var Text = $(this).val();
    $(this).val("");
    var j = "checkbox" + i;

    $("tbody").append("<tr><td><div class='checkbox'><input type='checkbox' id='" + j + "'/><label> " + Text + "</label><label class='glyphicon glyphicon-trash' id='" + i + "'></label></div></td></tr>");
    i = i + 1;
  }
});
.checked {
  text-decoration: line-through;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
  <table class="table">
    <thead>
      <tr>
        <th>To Do List</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          <div class="checkbox">
            <input type="checkbox" id="checkbox1" /><label>Task 1</label><label class="glyphicon glyphicon-trash"></label>
          </div>
        </td>
      </tr>
      <tr>
        <td>
          <div class="checkbox">
            <input type="checkbox" id="checkbox2" /><label>Task 2</label><label class="glyphicon glyphicon-trash"></label>
          </div>
        </td>
      </tr>
      <tr>
        <td>
          <div class="checkbox">
            <input type="checkbox" id="checkbox3" /><label>Task 3</label><label class="glyphicon glyphicon-trash" id="3"></label>
          </div>
        </td>
      </tr>
    </tbody>
  </table>
  <div class="row">
    <input type="text" placeholder="Add New Todo">
  </div>
</div>

Answer №1

Utilize:

$('.container').on('click', '.elementClass', function() { 
  // code
});

since you are dynamically loading elements

$('.container').on('click', 'input[type="checkbox"]', function() {
  $(this).next('label').toggleClass('checked', '');
});

$('.container').on('click', '.glyphicon.glyphicon-trash', function() {
  $(this).closest("tr").remove();
});

var i = 4;

$('.container').on('keypress', "input[type='text']", function(event) {
  if (event.which === 13) {
    var Text = $(this).val();
    $(this).val("");
    var j = "checkbox" + i;

    $("tbody").append("<tr><td><div class='checkbox'><input type='checkbox' id='" + j + "'/><label> " + Text + "</label><label class='glyphicon glyphicon-trash' id='" + i + "'></label></div></td></tr>");
    i = i + 1;
  }
});
.checked {
  text-decoration: line-through;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
  <table class="table">
    <thead>
      <tr>
        <th>To Do List</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          <div class="checkbox">
            <input type="checkbox" id="checkbox1" /><label>Task 1</label><label class="glyphicon glyphicon-trash"></label>
          </div>
        </td>
      </tr>
      <tr>
        <td>
          <div class="checkbox">
            <input type="checkbox" id="checkbox2" /><label>Task 2</label><label class="glyphicon glyphicon-trash"></label>
          </div>
        </td>
      </tr>
      <tr>
        <td>
          <div class="checkbox">
            <input type="checkbox" id="checkbox3" /><label>Task 3</label><label class="glyphicon glyphicon-trash" id="3"></label>
          </div>
        </td>
      </tr>
    </tbody>
  </table>
  <div class="row">
    <input type="text" placeholder="Add New Todo">
  </div>
</div>

Answer №2

Utilize the global call function in jQuery.

$('table.table').on('keypress', "input[type='text']", function(event){
  if(event.which === 13){
    var Text = $(this).val();
    $(this).val("");
    var j="checkbox"+i;

    $("tbody").append("<tr><td><div class='checkbox'><input type='checkbox' id='"+j+"'/><label> " + Text + "</label><label class='glyphicon glyphicon-trash' id='"+i+"'></label></div></td></tr>");    
    i=i+1;
  }
});

Answer №3

The current click function you have in place will only attach the event to an existing parent element. To resolve this issue, you can utilize the document object ....

$(document).on('click','input[type="checkbox"]',function(){
      $(this).next('label').toggleClass('checked', '');
  });

$(document).on('click','.glyphicon.glyphicon-trash',function(){
      $(this).closest("tr").remove();
});

Answer №4

   By clicking on the "+" (plus) button, you can effortlessly add a new text box to your form.



        <html>
        <head>
        <title>Dynamic Form</title>
        <script language="javascript">
        function changeIt()
        {
        var i = 1;
        my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext'+ i>"

        }
        </script>
        </head>
        <body>

        <form name="form" action="post" method="">
        <input type="text" name=t1>
        <input type="button" value="+" onClick="changeIt()">
        <div id="my_div"></div>

        </body>



To view this in JSFiddle, click [here](https://jsfiddle.net/0k7uy2sp/)

Answer №5

To achieve the desired functionality, you must use the event handler delegation method on('click'). The following code snippets demonstrate how you can handle the click events:

$('tbody').on('click', 'input[type="checkbox"]', function() {
    $(this).next('label').toggleClass('checked', '');
});

and

$('tbody').on('click', '.glyphicon.glyphicon-trash', function(){
  $(this).closest("tr").remove();
});

$('tbody').on('click', 'input[type="checkbox"]', function() {
  $(this).next('label').toggleClass('checked', '');
});

$('tbody').on('click', '.glyphicon.glyphicon-trash', function() {
  $(this).closest("tr").remove();
});

var i = 4;

$("input[type='text']").keypress(function(event) {
  if (event.which === 13) {
    var Text = $(this).val();
    $(this).val("");
    var j = "checkbox" + i;

    $("tbody").append("<tr><td><div class='checkbox'><input type='checkbox' id='" + j + "'/><label> " + Text + "</label><label class='glyphicon glyphicon-trash' id='" + i + "'></label></div></td></tr>");
    i = i + 1;
  }
});
.checked {
  text-decoration: line-through;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
  <table class="table">
    <thead>
      <tr>
        <th>To Do List</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          <div class="checkbox">
            <input type="checkbox" id="checkbox1" /><label>Task 1</label><label class="glyphicon glyphicon-trash"></label>
          </div>
        </td>
      </tr>
      <tr>
        <td>
          <div class="checkbox">
            <input type="checkbox" id="checkbox2" /><label>Task 2</label><label class="glyphicon glyphicon-trash"></label>
          </div>
        </td>
      </tr>
      <tr>
        <td>
          <div class="checkbox">
            <input type="checkbox" id="checkbox3" /><label>Task 3</label><label class="glyphicon glyphicon-trash" id="3"></label>
          </div>
        </td>
      </tr>
    </tbody>
  </table>
  <div class="row">
    <input type="text" placeholder="Add New Todo">
  </div>
</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

Materriel-UI ToggleButton has the appearance of a traditional button

Looking to style a ToggleButton like a button? Having trouble with an error in the console when nesting a button inside? Check out this solution: const StyledToggleButtonGroup = withStyles((theme) => ({ grouped: { margin: theme.spacing(0.5) ...

How come my Ajax call is setting the 'Content-Type' to 'application/x-www-form-urlencoded' instead of 'JSON' as specified in the dataType parameter?

I have encountered an issue while responding to a button click using the code snippet below. The console.log() confirms that the function is being called, but the HTTP request it generates contains the header "Content-Type: application/x-www-form-urlencode ...

Adapting npm scripts with Node.js based on the current context

Can you set up package.json to execute a different npm start script depending on the context? For instance, I want to run DEBUG=http nodemon app.js during development. However, I prefer to run node app.js in production. ...

Executing Javascript prior to Gatsby page load

Currently, I am in the process of converting an HTML template using Bootstrap 5 into a Gatsby template. While the CSS and pages are functioning as expected, I have encountered an issue with the inclusion of a main.js file within the HTML template that need ...

The Vue.js transition feature seems to be malfunctioning when trying to display a modal

I can't figure out why my animation isn't working with Vue transitions. Here is the code I have: <template> <teleport to="body"> <div class="modal-overlay" v-if="loading"> <transitio ...

Extract a value from a JSON object and store it in a JavaScript variable

While I understand how to input an entire JSON object into Javascript, I am unsure of how to extract a single object value and store it in a Javascript variable. For instance, if I wanted to store the value of "start_time" from the JSON object below in a ...

React Timer App: The setInterval function is being reset after each render operation

I'm currently working on a straightforward timer application that will begin counting seconds when a button is clicked. To implement this, I am utilizing react hooks. import React, { useState } from 'react' function Timer() { const [sec ...

What is the reason for this basic callback running before the setTimeout function?

Interesting behavior is observed in this code, where 'output 2' is logged before 'output 1' due to the setTimeout function. const func1 = () => { setTimeout(() => { console.log('output 1'); }, 3000); }; con ...

When attempting to modify an object that was initialized outside of a function, I am unable to change its value, or sometimes the function may not run at all. This

Currently in the process of constructing a social network utilizing nodejs, my knowledge on the subject matter is quite novice. This marks my initial discourse on the topic, and I would greatly appreciate your comprehension. Within my social network frame ...

Moving from one page to another

I am attempting to create a transition effect between sections within a single-page application. All the sections are contained on the same page, with only one section displayed at a time while the rest are set to display none. When a specific event is tri ...

Is it possible to share data from one controller in a JS file to another JS file? (using AngularJS)

I need to create a table in JavaScript. In one of my JS files, I have a controller with JSON data containing properties like width, height, color, etc. In another JS file, I am building the actual table structure. Here is an example of my AngularJS file: ...

What is the best way to flatten object literal properties?

I have received an object from a legacy server that I need to restructure on the client-side using JavaScript, jQuery, or Underscore.js. Here is the original structure of the object: [ { "Id":{ "LValue":1, "Value":1 }, ...

Positioning two divs to the right of another div

I am facing an issue with aligning the menu and categories divs to the right of the logo div in the following example: jsfiddle. I want them to remain stacked one under another as they are currently, but I am unable to achieve the desired display. Any ass ...

Is there a way for me to insert a new column into a table using jinja?

As a beginner in the final project of CS50x, I am working on creating a webpage that allows users to input weights into a database table and then view those weights along with weight gain/loss information. I am using jinja and python to render a query resu ...

Text in Angular vanishes upon reopening

I have a code snippet where I am trying to allow the user to edit and save a paragraph displayed on a side panel of the main page. Although the code works fine, allowing users to update the text and see it reflected in the network upon saving, there seems ...

Ways to extract information from PayFast

One issue I'm facing with my online store is that although PayFast does call my notify_url, it appears that no data is being posted. Below are the codes I've been using: Code for purchasing: <button id="cCart" type="submit" class="bt ...

Transform the structure of an object using Ramda from its original form

Is it possible to transform an object by modifying and filtering it to create a different shape that is easier to work with after making an API request? I've been struggling to find elegant solutions that don't involve using path and prop for eve ...

"Troubleshooting issues with the Updater function within the variable context API in React Native

I am in need of assistance as I am currently developing a survey system. The challenges I face involve creating surveys with an undetermined number of questions, requiring dynamic rendering based on the type of question (select, text, numeric, etc.). To ad ...

How to Maintain Hover State After Leaving an Element in jQuery?

1. I am working on a website with two menus, "Main" and "Sub". When you hover over a specific link in the main menu, it highlights the corresponding link in the sub-menu by adding a class to it. However, the issue is that when I move my cursor off the main ...

Creating a dynamic layout of 9 divs in a fluid 3x3 grid

Fiddle | FullScreen UPDATE : New Fiddle | FullScreen View The code snippet provided demonstrates the creation of a grid with dimensions of 3x3, consisting of 9 div elements (with 8 cloned using jQuery). The horizontal alignment of the grid has been ac ...