Changing the ID of a textbox can be done by modifying the corresponding

I need to dynamically generate textboxes, checkboxes, and buttons based on user input during runtime.

Users should be able to delete a specific textbox, checkbox, and button by clicking a button.

The creation process is working correctly.

However, when a user deletes one of the textboxes and associated elements, the remaining IDs should be updated accordingly, but this functionality is currently not functioning as expected.

for(i = 0; i <= k; i++) { 
    if (document.getElementById("cbox" + i).checked == true) { 
        var n = i.toString()   
        var textbox = document.createElement('input');
        textbox.type = 'text'; 
        textbox.id = "tbox" + i;
        textbox.value = document.getElementById("texts" + i).value;    

        document.getElementById('frm').appendChild(textbox);

        var cb = document.createElement('input');
        cb.type = 'checkbox';
        cb.checked = true;  
        cb.id = 'cbid' + i;
        document.getElementById('frm').appendChild(cb);    

        var btn = document.createElement('input');     
        btn.type = 'button';    
        btn.value = 'delete';   
        btn.name = 'delete';    
        btn.id = i.toString();  
        btn.onclick = function () {    
            var tbx = "tbox" + this.id;
            var cbx = "cbid" + this.id;
            var btndel = this.id;
            var x;                  

            (elem = document.getElementById(tbx)).parentNode.removeChild(elem);
            (elem = document.getElementById(cbx)).parentNode.removeChild(elem);
            (elem = document.getElementById(btndel)).parentNode.removeChild(elem);                

            for(x = btndel + 1; x <= 10; x++) { 
                document.getElementById('tbox' + x).id = "tbox" + (x - 1);
                document.getElementById("cbid" + x).id = "cbid" + (x - 1);
                document.getElementById(x).id = x - 1;
            }

            document.getElementById('frm').appendChild(btn);
        };

Answer №1

  var totalElem = 20
        for (i = 0; i <= totalElem; i++) {
            if (document.getElementById("cbox" + i).checked == true) {
                var n = i.toString()
                var textbox = document.createElement('input');
                textbox.type = 'text';
                textbox.id = "tbox" + i;
                textbox.value = document.getElementById("texts").value;
                document.getElementById('frm').appendChild(textbox);
                var cb = document.createElement('input');
                cb.type = 'checkbox';
                cb.checked = true;
                cb.id = 'cbid' + i;
                document.getElementById('frm').appendChild(cb);
                var btn = document.createElement('input');
                btn.type = 'button';
                btn.value = 'delete';
                btn.name = 'delete';
                btn.id = i.toString();
                btn.onclick = function () {
                    var tbx = "tbox" + this.id;
                    var cbx = "cbid" + this.id;
                    var btndel = this.id;
                    var x = btndel;
                    (elem = document.getElementById(tbx)).parentNode.removeChild(elem);
                    (elem = document.getElementById(cbx)).parentNode.removeChild(elem);
                    (elem = document.getElementById(btndel)).parentNode.removeChild(elem);
                    for (x = parseInt(btndel) + 1; x <= totalElem; x++) {
                        document.getElementById('tbox' + x).id = "tbox" + (x - 1);
                        document.getElementById("cbid" + x).id = "cbid" + (x - 1);
                        document.getElementById(x).id = x - 1;
                    }
                    totalElem -= 1;

                };
                document.getElementById('frm').appendChild(btn);

            }
        }

Give this solution a try and see how it works for you.

Answer №2

With the power of jQuery, achieving this task is a breeze.

//HTML:
<div id="dynamicContent"><p></p></div>

//jQuery
<script>
    $(document).ready(function(){
        var numOfElements = 4;
        var elementsString ="";
        for(var j =0; j<numOfElements; j++)
            elementsString = elementsString + "<input type='checkbox' id='check"+j+"'/><input type='text' id='text"+j+"'/><br/>";
        $("#dynamicContent p").html(elementsString);
    });
</script>

Answer №3

To manage the total count of TextBoxes and their corresponding CheckBox, it is essential to maintain a global variable.


var totalCount = 0;
for (i = 0; i <= k; i++) {
    if (document.getElementById("cbox" + i).checked == true) {
        var num = i.toString()
        var textboxElement = document.createElement('input');
        textboxElement.type = 'text';
        textboxElement.id = "tbox" + i;
        textboxElement.value = document.getElementById("texts" + i).value;
        document.getElementById('frm').appendChild(textboxElement);

        var checkboxElement = document.createElement('input');
        checkboxElement.type = 'checkbox';
        checkboxElement.checked = true;
        checkboxElement.id = 'cbid' + i;
        document.getElementById('frm').appendChild(checkboxElement);

        var deleteBtn = document.createElement('input');
        deleteBtn.type = 'button';
        deleteBtn.value = 'delete';
        deleteBtn.name = 'delete';
        deleteBtn.id = i.toString();

        //increment count
        totalCount++;
        deleteBtn.onclick = function() {
            var textBoxId = "tbox" + this.id;
            var checkBoxId = "cbid" + this.id;
            var btnDelete = this.id;
            var index;
            (element = document.getElementById(textBoxId)).parentNode.removeChild(element);
            (element = document.getElementById(checkBoxId)).parentNode.removeChild(element);
            (element = document.getElementById(btnDelete)).parentNode.removeChild(element);
            for (index = 0; index < totalCount; index++) {
                document.getElementById('tbox' + index).id = "tbox" + index;
                document.getElementById("cbid" + index).id = "cbid" + index;
                document.getElementById(index).id = index;
            }
            document.getElementById('frm').appendChild(deleteBtn);
        };

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

Guide on deploying Google App Script add-ons on Google Workspace Marketplace

Recently delving into Google App Script, I've taken my first steps in coding within the platform. Utilizing the deploy option provided by Google App Script, I successfully launched my app. However, upon deployment, I encountered difficulty locating my ...

Troublesome GSP: JavaScript not functioning properly in Gr

I am experiencing an issue with the JavaScript code I have. Here's my code: <script type="text/javascript"><!-- ​$(function () { $('#add').click(function() { $(this).before($('select:eq(0)').clone()); ...

Encountering issues importing Ace Document Object in a Vue webpack project?

In my Vue and Webpack project, I am trying to incorporate the Ace editor. My goal is to associate each file with a single instance of an Ace Document. To achieve this, I followed the default import method: import Ace from 'ace-builds' When atte ...

Accordion is having trouble expanding fully

My accordion is causing some trouble. When I try to open one section, both sections end up opening. I want it to toggle, so that only one section opens at a time based on my click. Switching the display from flex to column fixes the issue, but I don' ...

The IDE is showing an error, but Jest is able to run it flawlessly

I recently created a Jest unit test for a TypeScript function called checkEmail, which internally uses showAlert. The showAlert function in the utils.ts file looks like this: export const showAlert = (message: string) => { toast(message); }; In my ...

A link is not allowed to be a child of another link

An issue arises in a React.js application Warning: validateDOMNesting(...): <a> cannot be nested under another <a>. Refer to Element > a > ... > a for more information. What is the significance of this warning? How can it be avoided ...

The Videojs controls are unresponsive to clicks

Having a strange issue with videojs. I've been attempting to load videojs in the same way as outlined in the documentation, using a dynamic video tag. videojs(document.getElementById('myVideo'), { "controls": true, "autoplay": false, "prelo ...

Smooth transitions between points in animations using the D3 easing function

I'm working on an animated line chart that displays data related to play activities. I've been experimenting with changing the animation style between data points on the chart using d3.ease Currently, my code looks like this: path .attr("stro ...

Accessing JSON files locally using JavaScript in IE and Firefox

I am a beginner in JavaScript and currently working on a small HTML page that will be run locally. I have a string in JSON format that I need to store and load as a file on the hard drive. I have managed to store the string using the following code snippe ...

CustomTooltips in ChartJS allowing for an enhanced visual presentation of data

I am encountering an issue with my code where I am trying to incorporate images into custom tooltips. The goal is to dynamically generate PNG filenames based on the tooltip name or ID, but I am struggling to find unique values to assign as filenames for ea ...

Storing values in an array when checkboxes are selected within an ng-repeat loop in AngularJS

I am facing a situation where I need to populate an array with values when a checkbox is checked within an ng-repeat iteration. <li ng-repeat="player in team.players"> <div class="row"> <div class="col-md-3 m-t-xs"> <inp ...

A PHP tag containing a div element

As someone who is new to web development, I have a question that may seem silly to some. I am familiar with adding div tags inside php tags, but I am unsure if it's possible to add onclick functions or any other type of function to these div tags. He ...

Error Message: SCRIPT5 - Permission Denied When Trying to Open PDF with Javascript

Despite searching through multiple posts on SO, I have yet to find a solution to my issue. We operate a web form within our LAN that utilizes Javascript's OPEN function to open PDF files. Up until recently, everything was working smoothly. However, ...

Receiving an `Invalid module name in augmentation` error is a common issue when using the DefaultTheme in Material

After following the guidelines outlined in the migration documentation (v4 to v5), I have implemented the changes in my theme: import { createTheme, Theme } from '@mui/material/styles' import { grey } from '@mui/material/colors' declar ...

Is there a way to prevent Chrome from highlighting text that matches the content of a `position: fixed` element?

I currently have a Toc element in my HTML with the property position: fixed. (This means it remains in place as you scroll) My goal is to prevent Chrome's Find Text feature from recognizing text within that Toc element. (Ideally using JavaScript) ...

The form response values consistently show as undefined, attempting to send them to the backend with no success so far after trying two different approaches

I've tried approaching this issue in two different ways, but both times I end up with a value of "undefined" instead of the user input from the form. Just to give some context, I'm using material UI forms for this project. The first approach inv ...

Ensuring grid columns are equal for varying text sizes

I am looking to achieve equal width and spacing for columns without using the width, min-width, max-width properties. Can anyone help me accomplish this using flex or any other method? https://i.sstatic.net/xo56M.png .d-flex { display: flex; } .d-fl ...

Utilizing scroll functionality within a DIV container

I have the following Javascript code that enables infinite scrolling on a webpage. Now, I am looking to implement this feature within a specific DIV element. How can I modify this code to achieve infinite scroll functionality inside a DIV? Any assistance ...

Unable to view Bootstrap Icons in Gulp 4

I recently integrated the new bootstrap icons npm package into my project using Gulp 4, the latest version. Everything was installed successfully and was working smoothly. However, I encountered an issue when trying to declare the icon in my index.html fi ...

Troubleshooting Knockout.JS: Why self.myObservable is not working and the importance of code organization

My webpage uses knockout to handle a search field, dropdown selection, and page number. These elements are all initialized with default values for the first run or when the page is accessed. I'm encountering an error that says: "self.selectedTeamId i ...