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

Displaying related data in Codeigniter directly in the view from the model

What is the best way to utilize AJAX for displaying data from model mdl_request in a view? This function is part of my model: function retrieveUnitMeasurementByID($id){ $this->db->from('items', 'item_unit'); $this-> ...

Alter the data displayed by the Radio button using Angular when the Submit button is clicked

I've encountered an issue where I need to alter a div based on the selection of a radio button. Currently, it changes instantly upon button click, rather than waiting for submission. My desired outcome is for the value to be submitted when the button ...

displaying several gltf 3D models simultaneously on a map using mapbox gl and three js

Recently, I encountered an issue with adding glTF 3D models to a map using Mapbox GL and Three.js. It seems that while I can successfully add a single glTF model in a separate layer on the map, I am facing difficulties when trying to add multiple glTF mode ...

Is it necessary to include parentheses when utilizing a named function as a jQuery ajax success callback?

Is it necessary to include parentheses when specifying a function as a success callback if it was defined earlier? What impact does including or not including parentheses have? For example: function fish_food(){//do something} $.ajax({ url: '/ ...

What is the best way to set up multiple pagination instances for a single model/controller in CakePHP?

I'm facing a challenge with setting up a view that includes two different actions for the same model - one displays an item list sorted by the most recent, while the other shows the same list sorted by popularity. I want to paginate one list with 8 it ...

Unable to successfully call a directive function from a nested child directive

I'm facing a challenge with utilizing a directive that was created by another developer to notify my directive when the ngRepeat inside of it has completed its creation. My parent directive has an isolate scope and includes a function within its scop ...

Tips for updating a div element while maintaining its style and select2 plugin functionality with jQuery

Within the HTML code, I am attempting to refresh the following div: <select name="test[]" id="test" multiple required class="select2"> @foreach($tests as $s) ...

create a recurring design wallpaper within the TinyMCE editor

One of my functions alters the background of the tinymce editor. However, I am interested in having a wallpaper repeat in a similar fashion to background-repeat: repeat; in CSS. How can I achieve this? Here is the function: function SettinymceImage(bg_i ...

Suggestions for a JavaScript tool that automatically crops images

Is there a tool available, either browser-based or in Java, that can analyze an uploaded image, identify different characters within it, and crop them out into separate images? For instance, if this image contains three unique runic symbols, I would like ...

The image will come to life with animation as the background position is adjusted using Skrollr

Trying to create a div that switches the background image every X pixels scrolled. Initially experimented with changing the background-image, including using sprites and adjusting background position, but encountered a distracting "flickering" effect. Exa ...

Updating a MongoDB subarray with $set now includes adding a new entry rather than just updating existing ones

When trying to update an object in a sub-array, instead of replacing and updating the data, it adds a new entry. Here is the code from controller.js: const updateSubCategory = asyncHandler(async (req, res) => { const { dataArray } = req.body ...

Experiencing erratic outcomes with window.innerWidth in Mobile Safari

I am currently using JavaScript to determine the width of the browser: $(document).ready(function(){ var width = window.innerWidth; }); However, it seems that this method is producing inconsistent results. To showcase the issue, I have created a fun ...

The `process` variable is not recognized in a Vue/TypeScript component

I've encountered an issue trying to use .env variables in my Vue app. When I ran npm install process, the only syntax that didn't result in an error when importing was: import * as process from 'process'; Prior to this, I received the ...

The function createReadStream completes execution without resolving

Currently, I am in the process of developing a program that is aimed at iterating through files within a specified directory in a Linux environment. I have implemented a custom function called "myReadFile" which returns a new promise, and it is expected ...

Error encountered in Pokemon API: Trying to access property '0' of undefined

My current challenge involves accessing the abilities of my Pokemon, but I keep encountering a recurring error. In my project development using React hooks, I fetched data from the Pokemon API and stored it in setWildPokemon. Utilizing wildPokemon.name suc ...

What is the solution to fixing the Vetur/Vuelidate issue where the error message "'validate' does not exist in type 'ComponentOptions<Vue [etc.]" is displayed?

QUERY: I'm facing an issue with error 'validations' does not exist in type 'ComponentOptions<Vue [etc.] when using Vetur with TypeScript installed in VSCode. How can I resolve this? CONTEXT: I integrated Vuelidate into a single-file ...

Even though I have the image button's ID, I am unable to successfully click on it

I am facing an issue where I can't seem to click on an image button even though I know its ID: driver.findElement(By.id("its Id")).click() Unfortunately, I cannot provide the website link as it is not a public website. However, I have pasted the HTM ...

The duplication of HTML elements by mod_rewrite results in the disruption of the page's

Recently, I attempted to use mod_rewrite to change the structure of my URL. The original URL looked like this: main/index.php?board=announcements After implementing mod_rewrite, it now appears as: main/board/announcements Important note: There is no phys ...

Display data in a template upon receiving a response from the server

Hello, I am currently in the process of developing my very first Angular application and could use some assistance. Specifically, I am working on a component that serves as an image search box. When a user inputs a search query, a request is sent to an API ...

Instructions on how to eliminate the minutes button from Material UI datetime picker

I'm currently working on customizing a datetimepicker from materialUI in ReactJS. My goal is to prevent the user from seeing or selecting minutes in the picker interface. Despite setting the views prop to include only year, month, date, and hours, use ...