Creating an undo feature for a dynamically generated checklist of checkboxes

I am using a combination of javascript/jquery and html to dynamically populate the page with checkboxes. When you click "add", a new checkbox is created. I am now looking for a way to add an undo button that would delete the last checkbox created.

Here is a link to my code on JSFiddle:

My code on JSFiddle

Code snippet:

$(document).ready(function() {
  $('#btnSave').click(function() {
    addCheckbox($('#txtName').val());
    txtName.value="";
  });
});

function addCheckbox(name) {
  var container = $('#cblist');
  var inputs = container.find('input');
  var id = inputs.length+1;

  $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
  $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
  $('<br/>').appendTo(container);
}

Answer №1

Visit this link

Here is the HTML code for a New CheckList Template:

<h1 id="tit">New CheckList Template </h1>
<hr><br>

<form action="page being sent to">
Company Name: <input type="text" name="FirstName" value=""><br><br>

<div id="cblist">

</div>
<br>
<input type="text" id="txtName" />
<input type="button" value="Add Checkbox" id="btnSave" />
<input type="button" value="Remove Checkbox" id="btnRemove" />
<br>
<br>
<input type="submit" value="Save Company Template">
<input TYPE="button" onClick="history.go(0)" VALUE="Restart Template">
</form>

And here is the JS code that goes along with it:

 $(document).ready(function() {
        $('#btnSave').click(function() {
            addCheckbox($('#txtName').val());
             txtName.value="";
        });
        $("#btnRemove").click(removeCheckbox);

    });

    function addCheckbox(name) {
       var container = $('#cblist');
       var inputs = container.find('input');
       var id = inputs.length+1;

       $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
       $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
       $('<br/>').appendTo(container);

    }

    function removeCheckbox(){
        var container = $('#cblist');
        container.children('input').last().remove();
        container.children('label').last().remove();
        container.children('br').last().remove();
    }

Answer №2

Ensure that your newly added elements are enclosed in a small container before attaching them to the cblist. When deleting the last checkbox, make sure to delete the container along with the label and line break element as well:

$(document).ready(function() {
  $('#btnSave').click(function() {
    addCheckbox($('#txtName').val());
    txtName.value = "";
  });
  $('#btnRemove').click(function() {
    $(".New_CB").last().remove();
  });
});

function addCheckbox(name) {
  var container = $('#cblist');
  var inputs = container.find('input');
  var id = inputs.length + 1;

  var CBContainer = $("<span class='New_CB'/>");
  $('<input />', {
    type: 'checkbox',
    id: 'cb' + id,
    value: name
  }).appendTo(CBContainer);
  $('<label />', {
    'for': 'cb' + id,
    text: name
  }).appendTo(CBContainer);
  $('<br/>').appendTo(CBContainer);
  CBContainer.appendTo(container);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h1 id="tit">New CheckList Template </h1>
<hr>
<br>

<form action="page being sent to">
  Company Name:
  <input type="text" name="FirstName" value="">
  <br>
  <br>
  <div id="cblist">
  </div>
  <br>
  <input type="text" id="txtName" />
  <input type="button" value="Add Checkbox" id="btnSave" />
  <input type="button" value="Remove Checkbox" id="btnRemove" />
  <br>
  <br>
  <input type="submit" value="Save Company Template">
  <input TYPE="button" onClick="history.go(0)" VALUE="Restart Template">
</form>

Answer №3

To implement a removal feature, include a button that triggers the elimination of the last checkbox input when clicked:

$('#remove').click(function(){
    $('#cblist input').last().remove();
    $('#cblist label').last().remove();
    $('#cblist br').last().remove();
});

Answer №4

Locate and delete the most recent checkbox that was added.

JavaScript :

$(document).ready(function() {
    $('#btnSave').click(function() {
        addCheckbox($('#txtName').val());
         txtName.value="";
    });
    $('#removeCheckbox').click(function(){
    var cb=$( "#cblist input" ).last();
    if(cb && cb.length){
       cb.remove();
    }
});
});
function addCheckbox(name) {
   var container = $('#cblist');
   var inputs = container.find('input');
   var id = inputs.length+1;

   checkbox= $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
   $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
   $('<br/>').appendTo(container);

}

HTML :

<h1 id="tit">New CheckList Template </h1>
<hr><br>

<form action="page being sent to">
Company Name: <input type="text" name="FirstName" value=""><br><br>




<div id="cblist">

</div>
<br>
<input type="text" id="txtName" />
<input type="button" value="Add Checkbox" id="btnSave" />
<input type="button" value="Remove Checkbox" id="removeCheckbox" />
<br>
<br>
<input type="submit" value="Save Company Template">
<input TYPE="button" onClick="history.go(0)" VALUE="Restart Template">
</form>

Demo : https://jsfiddle.net/vikashvverma/kf2mq20e/10/

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

determine function output based on input type

Here's a question that is somewhat similar to TypeScript function return type based on input parameter, but with a twist involving promises. The scenario is as follows: if the input is a string, then the method returns a PlaylistEntity, otherwise it ...

Create a dynamic animation using Angular to smoothly move a div element across the

I currently have a div with the following content: <div ng-style="{'left': PageMap.ColumnWrap.OverviewPanelLeft + 'px'}"></div> Whenever I press the right key, an event is triggered to change the PageMap.ColumnWrap.Overvie ...

Creating a dynamic webpage where multiple images are displayed on a single canvas using

I'm currently working on a chess project where I'm using a canvas to create the game board and draw 32 chess pieces on it. To update the screen when a piece moves, I've implemented requestAnimFrame. However, I'm facing an issue where th ...

Displaying images in a carousel below a fixed navigation bar using Bootstrap

Check out my website at When viewing on smaller screens like mobile devices, I'm facing issues with my carousel images overlapping the navbar. Any suggestions on how to keep them below the navbar? Also, the third image appears shorter in length compa ...

The fancybox scroll feature is visible when using a browser, but unfortunately, it does not appear on the

I noticed that the scrollbar in my fancybox is not showing up on iPad, but it does display when using Google Chrome on Desktop. You can find the page here. The issue seems to be with the vertical scroll bar not appearing on iPad. Has anyone encountered th ...

Guide on incorporating a dropdown menu within a Jssor slider

I am facing an issue with trying to include a dropdown menu inside the Jssor slider. The menu does not drop down when placed inside it. Here is the code snippet: <head> <script src="jquery.js"></script> <script src="jssor.slider.min. ...

Creating a personalized pivot-table using the WebDataRock Javascript library with a unique configuration based on a

I'm having trouble getting this demo to work with the "hierarchy" parameter. Even when I specify the parameter value, it seems to apply the condition to the entire hierarchy chain. "conditions": [{ "formula": "#val ...

ERROR: Module 're2' not found in './build/Release/re2' (npm)

After receiving suggestions from sonarQube, I am attempting to switch out my original regular expression with RE2. However, upon installation, the following error message appears: Error: Cannot locate module './build/Release/re2' Important note ...

"Relating to meteorjs, admin users are akin to those in

Looking for a package or tutorial to create admin users similar to Django. I want to be able to create superusers through the terminal and have the ability to personalize user schemas with Collection2. Additionally, I would like to remove the option for ...

What is the best way to ensure that the text within Span children is properly laid out to match the width of the parent div tag?

This particular instance involves setting the width of the div tag to 200px and organizing all the span children to occupy the entire width of the parent div tag. If the first row is filled, the span tags should then flow into a second row. My attempt at ...

What is the best way to pick out specific passages of text

I'm attempting to create an autocomplete feature where the data is displayed in a div below the text box as the user types. While this typically involves ajax, I've simplified the approach without using jQuery autocomplete. Once the text appears ...

What steps can I take to create a responsive jQuery UI buttonset?

I am currently facing a challenge with my web app (http://www.tntech.edu/cafe-menu.php) which is being iframed into a mobile application developed by ATT. The button sizes vary on different phone models, and I am seeking a solution to make them responsiv ...

The connection between MongoClient and Express has been established successfully, however, an error occcurred: TypeError: Cannot read the property 'collection' of null

I am currently working with the MongoClient instead of mongoose, but I am facing an issue where I can't seem to set a new collection in my routes file. db/index.js const {MongoClient} = require('mongodb'); const MONGO_DB_NAME = 'mooo ...

The NextJS Link component does not seem to be receiving the styles from Tailwindcss

I am currently working on a nextjs frontend project that has tailwindcss integrated. Below is an example of the code I am using: import Link from 'next/link' return( <div> <Link className="text-sm hover:text-gray-600" ...

Tips for showcasing a designated set of numbers in Vue Js while iterating?

Is there a way to specifically target numbers during a loop? For example, I only want to retrieve numbers 5 and above or within a certain range that I specify. <select name="" id="input" class="form-control" v-model="selectcompetitionyear"> < ...

Utilizing a variable within an Angular filter: A step-by-step guide

Currently, I am in the process of experimenting with Angular. I am able to retrieve some data from the controller and successfully apply a filter when passing it as a string. However, I encounter issues when attempting to use a variable for the filter inst ...

Comparing inline-block and block display options for displaying images

In this HTML snippet, there is a main div with the id of "main_div" that contains two sub-divs. The first sub-div has an id of "logo" and includes a link to a picture. The second sub-div has an id of "intro" and contains text. For reference, here is the o ...

Button click event not triggering JavaScript execution

I am experimenting with HTML, PHP and JS and have encountered a problem. Here is my code: <html> <head> <title> Dummy Code </title> <script> sendMail(){ <?php $to = '<a href="/cdn-cgi/l/email-protection" class ...

Align the Media center div within a column utilizing Bootstrap

I have a template in html with a media object containing a logo and text, both within a column of width 5. Currently, it is not centered and aligned to the left. I am looking for a way to centrally align the media block within the column, regardless of its ...

Transitioning from Bootstrap 4 to Bootstrap 5 raises concerns about container compatibility

Interested in transitioning from Bootstrap 4 to Bootstrap 5. Noticed that the container max-width appears different on the default setting. Any insight on why this is and how it can be adjusted to resemble Bootstrap 4? I'm a beginner with Bootstrap, s ...