What is the best way to empty input, select, and textarea fields after performing a clone operation

I am currently working on creating a form to display items and need a fresh text field when the user clicks the ADD button.

function addNewItem() { //ADD ROW AND CLONE
  var table = document.getElementById('tbl');
  var tbody = document.createElement('tbody'); 
  table.insertBefore(tbody, null);
  var clone = document.getElementById('cln').cloneNode(true);
  tbody.insertBefore(clone, null);
}

function deleteItem() { //DELETE ROW
  var table = document.getElementById('tbl');
  var delRow = table.rows.length;
  if (delRow > 1) {
    table.deleteRow(delRow - 1);
  }
}
<tr id="cln"> //CALL CLONE FUNCTION
  <div align="center">1</div>
  </td>
  
  // PHP Database Connection Code

I'm facing difficulties in setting up the text field value for when the user clicks the button. I want to use a cloning function instead of copying old values from the first row and column. Is there a way to make the index auto-increment?

EXAMPLE

Answer №1

If you want to reset form data, you can simply do the following:

document.querySelector("#myForm").reset();

Ensure that your form structure resembles this:

<form id="myForm">
   <input .....
</form>

Answer №2

One thing to note is that the cloned element will have unique IDs, such as adding -1 to the original ID.

Recently, I accomplished this task using jQuery and opted for string.replace(regex, '') instead of the method described here.

Here's an example that you can adjust to fit your specific scenario:

var clone = document.getElementById('id-of-element').cloneNode(true);

clone.childNodes[x].nextSibling.childNodes[y].value = '';

document.getElementById('target-element').insertBefore(clone, null);

Best regards,

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

Transforming Color with JQuery on the Fly

Check out this Jquery script that gradually changes the color of an object from (0, 0, 0) to (255, 255, 0). $(document).ready(function(){ var r = 0; var g = 0; changeColor(r, g); }); function changeColor(r, g){ var newColor = "(" + r + ", ...

Using Mongoose schema with a reference to an undefined 'ObjectID' data type

I am currently working on establishing relationships between my schemas, and I have encountered some issues with my solution. Here is how my device schema looks like: var deviceSchema = schema({ name : String, type : String, room: {type: mongo ...

Ways to define global variables with JavaScript

What is the correct way to create a global variable in JavaScript that is available throughout the entire HTML document? Is it possible to access a variable declared in one script from another? ...

When you try to upload an image using php/ajax, it causes the page to refresh

I'm currently experiencing an issue with my script. I am successfully using formData() to upload an image via Ajax, which is being saved to the designated folder. However, I am puzzled as to why my page keeps refreshing after move_uploaded_file() is e ...

Retrieving components from Ajax response data

While I have a good grasp of PHP, diving into AJAX and dealing with JSON is proving to be quite challenging for me. My PHP script simply delivers a straightforward JSON string like this: {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": ...

Unknown individual, yet revealed by the investigator

I'm attempting to develop a dynamic list in react.js generateList = () =>{ return this.state.user.map((u)=>{ console.log(u); return <li onClick={this.handleClick} id={u} name={u}>{u}</li>; }); } The hand ...

Ways to mix up a term while maintaining the original first and final characters intact (Javascript)

I've been given a task to shuffle a word that has more than 3 letters while keeping the first and last letters unchanged. The revised word should not be identical to the original, ensuring some sort of rearrangement is apparent. For example, when sh ...

Is it possible for an AngularJS directive to compile a fresh element that has a second directive assigned to it?

UPDATE: All directives listed below will now require ng-model bindings to be applied in the elements they generate, targeting the controller assigned to the page. The code has been modified to reflect this. I am exploring the creation of dynamic HTML usin ...

Changing letter cases in a textbox using Javascript

I have a challenge to create a code that can switch the case of text entered by the user. Here is what I currently have: var num; function toggleTextCase(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase( ...

I'm experiencing difficulties with JS on my website. Details are provided below – any suggestions on how to resolve this issue

Can someone help me with a web project issue I'm facing? Everything was going smoothly until I tried to add some JS for dynamic functionality. However, when I attempt to access my elements by tag name, ID, or class, they always return null or undefine ...

What is the best way to remove table cells from a TableBody?

Currently, I am in the process of designing a table to display data retrieved from my backend server. To accomplish this, I have opted to utilize the Table component provided by Material UI. The data I retrieve may either be empty or contain an object. My ...

Tips for accessing the value and text of an Angular Material mat-select through the use of *ngFor

When using a dropdown menu, I want to retrieve both the value and text of the selected option. View dropdown image Underneath the dropdown menu, I aim to display values in the format of "options: 'value' - 'selected option'". compone ...

What is the process of importing the csv-writer module?

Can we use the import statement instead of const createCSVWriter = require('csv-writer').createObjectCsvWriter; Is there a way to achieve this using import ...

Animating jQuery to adjust height based on a percentage

My animation using percentage is not working as expected. It expands to the whole height instantly instead of smoothly transitioning to 100%. Here is my CSS code: #block-views{ overflow:hidden; height:20px; } This is my HTML code: <div id="block-view ...

What does the HTML and JS code look like when using Next.Js?

Here's an illustration of the desired result: codepen.io/j0be/pen/jWGVvV How can I implement this HTML and JS in Next.js? I am looking to customize this code using TypeScript and SCSS in Next.js. However, I am unsure about how to convert the HTML an ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

Tips for validating and retrieving data from a radio button paired with an input box in reactjs

I'm diving into the world of React and facing a challenge with multiple radio buttons that have associated input fields, like in this image: https://i.stack.imgur.com/Upy3T.png Here's what I need: If a user checks a radio button with a ...

Integrating tilt and zoom functionality on a web page based on mouse movements

While browsing through some messages on chat, I came across something interesting: I noticed that as I moved my mouse left or right, the content would tilt in that direction, and when moving up and down, the content would zoom in or out. It was a really c ...

Is React Context suitable for use with containers too?

React provides an explanation for the use of Context feature Context in React allows data sharing that can be seen as "global" within a tree of components, like the authenticated user, theme, or language preference. Although this concept works well for ...

An error was thrown: Unexpected token ILLEGAL was detected

Working with Liferay 5.2 I would like to show a message related to the current language of Liferay. The code for this message is in Velocity language and can be found in navigation.vm file. <div id="navigation" class="sort-pages modify-pages"> ...