Remove a textbox dynamically in jQuery using solely jQuery without the use of traditional JavaScript code

My code is aimed at creating a dynamic way to add and remove textboxes. However, I am encountering a problem where clicking the delete button removes everything instead of just one textbox. Can anyone spot the error in my code or offer a solution to remove one textbox at a time? Your help is greatly appreciated. Thank you in advance!

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dynamic Textbox Addition</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>              
<script>
    $(document).ready(function () {
        $('<button/>').attr({ 'id': 'add' }).appendTo("body");
        $("#add").text("Add Field");
        $('<div/>').attr({ 'id': 'items' }).appendTo("body");
        $('<div/>').attr({ 'type': 'text', 'name': 'input[]' }).appendTo("#items");

        $("#add").click(function (e) {
            var text1 = $('<div/>').attr({ 'id':'div2','type': 'text', 'name': 'input[]' });
            var text2 = $('<input/>').attr({ 'id': 'i1', 'type': 'text', 'name': 'username', 'size': '25' });
            var text3 = $('<button/>').attr({ 'id': 'del' }).text("Delete");
            $("#div2").append(text2, text3);
            $("#items").append(text1);
            $('<br/>').insertAfter(text3);
        });

        //Delete function
        $("body").on("click","#del",function (e) {
            $(this).parent("div").remove();
        });       
    });      
   </script>
</head>
<body>

</body>
</html>

Answer №1

When it comes to jQuery, it's important to understand that it is essentially javascript. Here is the JSfiddle link for reference: http://jsfiddle.net/wfthf2qc/

An issue arose due to the repetitive use of the same id for all text fields (#div2), causing jQuery to continuously append to the first instance of #div2. Consequently, when the delete function was triggered, it removed the parent div containing all the fields.

In my revised code, I introduced a count variable that increments with each "add" button click. This variable was crucial in generating unique div names (div1, div2, div3, etc), which enabled jQuery to properly append the new field.

Additionally, I rearranged the order of operations by moving $("#items").append(text1); before

$("#div" + count).append(text2, text3);
. This adjustment was pivotal as placing it after resulted in the initial "add" button click failing due to the absence of div containers to append to.

$("#items").append(text1);
$("#div" + count).append(text2, text3);
$('<br/>').insertAfter(text3);

In conclusion, while there may exist a more refined solution for this issue, my intention was to maintain the essence of your original code without straying too far from it.

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

Express Server React 403 Forbidden Error

Issue: When attempting to make a post request using the AXIOS library in React, I am receiving a 403 (Forbidden) error for http://localhost:5004/api/auth/login. Despite having installed cors on Express, the console continues to display the 403 error. My c ...

Obtain textNames and colorNames data from a locally stored nested JSON file

I am currently working with a data.json file to fetch and display data in my HTML. Here is the code snippet of my Component: tooltip: any; tooltipColor: any; ngOnInit() { this.DataFactory.getLimitedData(this.widgetData).subscribe(data => { this ...

Tips for styling a React JS component class

I am attempting to write inline CSS for a React JS component called Login, but I keep encountering an error. What could be causing this issue? Could you provide guidance on the correct way to implement in-line component CSS? import React, {Component} from ...

Error: cannot use .json data with `filter` method from WEBPACK_IMPORTED_MODULE_2__["filter"]

There seems to be an error occurring when attempting to retrieve data from a JSON file in the specific line of code selectedEmployee: employeeList.data.Table[0], An issue is arising with TypeError: _employeeList_json__WEBPACK_IMPORTED_MODULE_2__.filter ...

Issue with Editing the Layout of a Recently Created Page in Django CMS

I am brand new to the world of Django CMS and currently facing an issue that has me stuck. After adding a new module to an existing Django project and creating a new HTML page, I encountered a challenge with the templates configuration in settings.py. TEM ...

Executing JavaScript code externally on Electron's local server

During local development, I prefer to store all of my separate JS scripts in a different folder. However, the only way I have found to do this is by omitting the declaration of the meta statement. Unfortunately, this omission triggers a warning message. ...

Guide on how to submit an image along with text using AJAX, PHP, and HTML

Hey there! I'm currently working on a project where I need to upload an image with comments added into a database using a combination of PHP, AJAX, and HTML. Let me show you the HTML part first: <form name="form1" enctype="multipart/form-data" ac ...

verifying the presence of offspring in knockout js

Utilizing knockout for displaying items on the page, I have a series of groups such as Group 1, Group 2, etc. Each group is contained within its own div. Upon clicking on a group, it expands to showcase the items within that specific group. However, some o ...

In Internet Explorer 8, the PNG image is visible but in IE7, it myster

I have been trying to showcase a logo (PNG created in Paint.NET) on my website (XHTML 1.0 Transitional), using the following code: <body> <div class="header"> <div class="logo"> <img src="logo.png" /> </div> ...

Validating multiple conditions in Typescript by passing them as function parameters

As a beginner in TS/JS, I am looking to validate multiple conditions passed as arguments to a function. For instance, currently I am verifying the user role name, but in the future, I may need to check other conditions. validateUserDetails(): Promise< ...

Warning: Potential critical dependency detected while utilizing react-pdf package

When attempting to showcase a PDF on my react application, I encountered the following warning: /node_modules/react-pdf/node_modules/pdfjs-dist/build/pdf.js Critical dependency: require function is used in a way in which dependencies cannot be static ...

How can Symfony, Jquery, and Ajax work together to append elements to themselves?

I've implemented a jQuery function that dynamically adds rows of data from one table to another table for submission. Essentially, when a user selects an item or items (a row) in the initial table, it gets duplicated in a separate area where they can ...

Creating a mobile-friendly split column layout with Bootstrap 5

I have a similar question to the one posed in this thread How to split Bootstrap column in mobile mode, but I am working with Bootstrap 5 and the previous solution using float: right no longer works due to flexbox. On desktop, I have two columns and I wan ...

Excessive white space on WordPress pages is creating a less than ideal

On my WordPress page, I have set up a row with the main side at span10 and the right sidebar at span2. However, the layout leaves too much blank space, causing users to scroll to the right and see nothing. You can view the specific page here Below is the ...

Gradually make the table row and its contents disappear as you scroll, based on how hidden the row is within the containing div

Uncertainty clouds my mind as to the practicality of this approach, the potential performance implications, and the frequency of scroll events firing to make this technique viable. Nevertheless, within a fixed height div (overflow-y: auto) lies a table. M ...

Is there a way to lock the eye icon in place within the password field using Vue.js?

I added an eye icon to the right side of my password input fields. However, occasionally error messages may pop up on the page to signify issues with the input fields. When these error messages appear below the relevant input field, the position of the eye ...

Does the use of CSS positioning impact the performance of browser rendering?

Given two DIVs, A and B, where A contains B, and the following CSS styles: A { margin-left: -2000px; } B { margin-left: 2000px; } With these CSS styles applied, the position of B remains unchanged compared to its original position without any CSS. I am c ...

What are the most effective strategies for managing vast amounts of data using JS fetch?

The server is taking about 2 minutes to export a large JSON data, resulting in a timeout error on the client side before receiving a response from the server. I have searched online for solutions, but I cannot find a way to extend the timeout or continue ...

Can you guide me on implementing CSS Houdini in Next.js?

Exploring the world of CSS Houdini in my Next.js project has been quite an adventure. After successfully installing the necessary CSS Houdini package and css-paint-polyfill using yarn, I decided to follow the webpack guidelines provided at . Below is a sn ...

What are the steps to incorporate PointerLockControl in Three.js?

Having trouble correctly integrating the PointerLockControl in Three.js? Despite trying various examples, errors seem to persist. I've been importing libraries through the head part like this: <script src="lib/controls/PointerLockControls.js"> ...