What is the best way to create an update function that allows an edit form to replace existing text with new content?

I'm struggling with creating a straightforward update function to edit an ingredient and save the changes. Despite my efforts, I can't seem to get it right. Every time I submit the form, I just end up with the same unchanged ingredient. Here is the code snippet:

editIngredient() {
  const ingredientId = this.parentElement.dataset.id;
  var editForm = 
    `<form id="edit-form">
       <input type="text" id="edit-input">
       <input type="submit" value="Edit Ingredient">
     </form>`;
  this.parentElement.insertAdjacentHTML('beforeend', editForm);
  console.log(this.parentElement);
  document.getElementById('edit-form');
  editForm.addEventListener("click", updateIngredient);
}
renderIngredient(ingredientList){
  const li = document.createElement('li');
  li.dataset.id = this.recipe_id;
  li.innerText = this.name;
        
  const deleteBtn = document.createElement('button');
  deleteBtn.addEventListener("click", this.deleteIngredient);
  deleteBtn.innerText = "X";
  li.appendChild(deleteBtn);
  ingredientList.appendChild(li);

  const editBtn = document.createElement('button');
  editBtn.addEventListener("click", this.editIngredient);
  editBtn.innerText = "Edit";
  li.appendChild(editBtn);
  ingredientList.appendChild(li);
}

I may be new at this and lacking in knowledge, but any assistance, example code, or useful resources would be greatly appreciated.

Answer №1

Check out this sample I created to help illustrate the concept:

HTML Example

<ul>
  <li id="sugar">
    <label>Sugar</label>
    <button>Edit</button>
  </li>
  <li id="spice">
    <label>Spice</label>
    <button>Edit</button>
  </li>
  <li id="everything-nice">
    <label>Everything Nice</label>
    <button>Edit</button>
  </li>
</ul>

<form id="update-form"&rt;
  <input type="hidden" name="ingredientId"/>
  <input type="text" name="ingredientName"/>
  <input type="submit" id="submit" value="Update" />
</form>

The HTML form consists of three input fields:

  1. A hidden field that stores the selected li's ID for editing. You can also use a JavaScript variable for this purpose.
  2. An input field for entering the updated value.
  3. Finally, a submit button to manage form submission.

Javascript Logic

const updateForm = document.querySelector("#update-form");

// Attach click event listeners to all edit buttons
// When clicked, set the input values in the update form accordingly.
document.querySelectorAll("li > button").forEach(el => {
  el.addEventListener('click', function(e) {
    let parentEl = e.target.parentElement;
    updateForm["ingredientName"].value = parentEl.querySelector("label").innerText;
    updateForm["ingredientId"].value = parentEl.id;
  });
});

// Handle form submission 
updateForm.addEventListener("submit", function(e) {
  e.preventDefault(); // Prevent default submission behavior
  
  let elementToUpdate = document.getElementById(this["ingredientId"].value);
  let updatedLabel = this["ingredientName"].value;
  elementToUpdate.querySelector("label").innerHTML = updatedLabel;
});

View it live on CodePen: https://codepen.io/nikkomina/pen/MWjzygo

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

Extract the image source from this HTML retrieved using JavaScript

I need to retrieve the source URL of an image from a certain part of a document. Here is my current approach: var theImg = document.getElementById('imageDiv').innerHTML; The above code snippet returns something like this: theImg = <img src ...

Error Occurs When Trying to Utilize Imported React Selector in React Actions Script

Desired Action: I am looking to utilize a state value within one of my action methods. Preferred Approach: Instead of directly referencing state.sale.oliver.data, I aim to abstract it by invoking my selector function, showingTest(state). Issue Encountere ...

Ajax request in Rails not receiving a response from the controller

After troubleshooting a simple GET request to the controller action, I confirmed that the request is being made successfully and there are no issues with the controller executing the action. However, I am not receiving any response data. $.ajax({ url: ...

Angular CORS problem when sending information to Google Forms

When submitting the data: Error Message: Unfortunately, an error occurred while trying to send the data. The XMLHttpRequest cannot load https://docs.google.com/forms/d/xxxxxxxxxxxxx/formResponse. The response to the preflight request did not pass the ac ...

NodeJS authentication using Express-Session and Passport encounters errors

I have successfully implemented authentication and login functionality using the Google OAuth API in my NodeJS backend. const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; ...

How can we efficiently trigger a function that sends an axios request by leveraging data from a v-for loop?

Currently, I am developing an e-commerce platform using Rails and VueJS. In order to display the orders of a specific user, I have created a component file. Within this component, I am utilizing a v-for loop to iterate over and showcase all the information ...

"Dropping a file into the Dropzone module will always result in the return of 'empty($_FILES)' being true

I'm currently working on a project that requires drag and drop functionality on my web page. My ultimate goal is to retrieve dropped images and upload them to my database. HTML <form action="parser.php" id="file-up" class="dropzone"> <in ...

Sliding in images with JQuery

I need help with animating the slide-in effect of 7 "card" images from the left to the center of the screen. I attempted to achieve this using the following code: function FetchCards() { $("#pack").css('margin-left', 0); $("#pack").css(& ...

Enquire.js does not compute accurately at first glance, but only after adjustments are made during

Currently, I am working on incorporating media queries using Enquire.js and Vue.js. The functionality seems to be in good shape when manually resizing the browser window. However, upon loading the document, no match is detected. This peculiar behavior beco ...

At random intervals, a ReferenceError is triggered stating that Vue is not defined

While working on an application that uses templates rendered by Apache Velocity, I encountered the error "Uncaught ReferenceError: Vue is not defined" when trying to incorporate vue.js components. Oddly enough, this error is not consistent - it occurs most ...

Turn on the text field when the enter key is pressed

I've searched online for solutions, but none of them have resolved my issue. Upon loading my page, I am able to successfully have my JS file select the first textfield. However, I am struggling with getting it to proceed to the next textfield when th ...

Modifying the value of a variable causes a ripple effect on the value of another variable that had been linked to it

After running the code below, I am receiving values from MongoDB in the 'docs' variable: collection.find({"Stories._id":ObjectID(storyId)}, {"Stories.$":1}, function (e, docs) { var results = docs; results[0].Stories = []; } I ...

The keyboard fails to open when trying to input text on a WKWebView

Is there a way to programmatically open the keyboard in a WkWebView for tel text input after a JavaScript function call? I want the keyboard to display for efficiency reasons when a certain input is activated, but it doesn't gain focus automatically. ...

Is utilizing v-model to update the Vuex store a recommended practice?

Hello there! As a newcomer to Vue, I find myself facing a dilemma that has been weighing on my mind. I'm confused about whether we should utilize the v-model directive to make changes to the Vuex store. While Vuex guidelines suggest modifying the stor ...

Is there a way to prevent a button from being clicked until a certain callback function is triggered

I am struggling with configuring my contact form to disable a button when the form is not valid or a recaptcha is not selected. <form name="contactForm" data-ng-controller="ContactCtrl" novalidate> ... <input class="form-control" name="email" typ ...

Unexpected Undefined Return in Request Parameters

Hey everyone, I'm currently working on setting up a mock API server using a JSON file with some dummy data. The first route I created is functioning perfectly: const express = require("express"); const router = express.Router(); const data = requir ...

Display JSON data retrieved from PHP script on Windows Phone 8.1 platform

After running a PHP file, I receive the following JSON data: {"Name":"Waqas","Age":37,"Address":"Kanju"} Interestingly, when I try to execute the same method on Windows Phone, I get the exact same JSON output: {"Name":"Waqas","Age":37,"Address":"Kanju"} ...

Is there a way to update protractor.conf.js configurations using the command line?

Currently, I have set up Protractor to run on our integration server. In the protractor.conf.js file, I have configured the multiCapabilities as follows: multiCapabilities: [{ 'browserName': 'firefox', 'platform': &a ...

Firebase Cloud Functions - Deleting the eldest offspring

I have created an onWrite cloud function that listens for updates made by a user. My goal is to delete the oldest child if there are more than three children present in the database. Here's where I currently stand: exports.removeOld = functions.datab ...

Error: JSONP unexpectedly encountered token '<' causing a SyntaxError

Issue: Error: Uncaught SyntaxError: Unexpected token < My Attempt Method Used: Jsonp Result: received XML Response 200. Due to Cross Domain Request, data type jsonp was utilized Code snippet: $.ajax({ url: "some url", headers: { ...