What is the best way to add a new li element to a ul list that shares the same class name

Is there a way to add a new li element to the ul on the right side? Each card comes with a ul and a form.

After submitting the form, I want to append a new li to the corresponding ul. Each ul has a class of .topics. However, the new li is currently being added to all cards.

I am struggling with finding a solution to append the li inside the correct ul where it was created.

This shows my HTML structure

<div class="card" id="card1">
  <div class="card-body">
   <ul class="topics">
       <li>....</li>
       <li>....</li>
       <li>....</li>
   </ul>
  </div>
  <div class="card-footer">
      <form method="post" class="topic-form">
          ....
      </form>
  </div>
</div>

<div class="card" id="card2">
  <div class="card-body">
   <ul class="topics">
       <li>....</li>
       <li>....</li>
       <li>....</li>
   </ul>
  </div>
  <div class="card-footer">
      <form method="post" class="topic-form">
          ....
      </form>
  </div>
</div>

This displays my JS code

$('form.topic-form').submit( function (e) {
   e.preventDefault();
   var form = $(this)[0];
   $.ajax({
          ...ajax stuff...        
      },
      success: function (json) {
          form.reset();
          $(".topics").append('<li>.....</li>')
      }
   }
}

Answer №1

This particular line is causing trouble

$(".categories").append('<li>.....</li>')

...is executing without specifying a specific context, and searching across the board. It should be narrowed down to the ul connected to the section that initiated the action. The most sensible approach would be to locate the nearest section element with a class of .box and work from there.

$(this).closest('.box').find('.categories').append('<li>.....</li>')

Answer №2

You must indicate the specific .topics you are referring to. In most cases, use $(this) (or form in your situation) to target the correct one.

$(this).closest('.card').find('.topics')

Answer №3

When submitting a form, first create a reference to the form using $currentForm = $(this);. Then, in the Ajax response, insert the li element by finding the parent card and appending it to the relevant topic:

$currentForm.parents(".card").find('.topics').append('<li>.....</li>');

It is important to note that the parents() method starts searching with the first parent element, while the closest() method starts with the element itself. There isn't much difference between them other than that.

Your Ajax code should look something like this:

$('form.topic-form').submit(function (e) {
      e.preventDefault();
      $currentForm = $(this);
      $.ajax({
            ...ajax stuff...        

       },
       success: function (json) {
            $currentForm.get(0).reset();
            // or $('form#myform').trigger("reset");
            $currentForm.parents(".card").find('.topics').append('<li>.....</li>');
      }
}

Here is a sample snippet to demonstrate this:

$(function() {
  $('form.topic-form').submit(function(e) {
      e.preventDefault();
      $currentForm = $(this);
      setTimeout(function() {
        let rand = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5)
      $currentForm.get(0).reset();
        $currentForm.parents(".card").find('.topics').append(`<li>${rand}</li>`);
      }, 1000);

  });
});
.card {
  width:45%;
  display:inline-block;
  border:1px solid black;
  vertical-align:top;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="card" id="card1">
  <div class="card-body">
    <ul class="topics">
      <li>FOO from1</li>
    </ul>
  </div>
  <div class="card-footer">
    <form method="post" class="topic-form">
      <button>add</button>
    </form>
  </div>
</div>

<div class="card" id="card2">
  <div class="card-body">
    <ul class="topics">
      <li>BAR form2</li>
    </ul>
  </div>
  <div class="card-footer">
    <form method="post" class="topic-form">
      <button>add</button>
    </form>
  </div>
</div>

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

What is the best way to set the width of an element to 100% while accounting for padding

My dilemma involves an HTML input field. The input currently has padding: 5px 10px;, but I need it to occupy 100% of its parent div's width (which is fluid). If I try using width: 100%;, the input ends up being wider than intended due to the padding ...

Error loading .OBJ files in Three.js on Azure, but works fine locally

I've been using three.js for webGL to load .obj files, but I'm facing an issue when trying to load .obj files on Windows Azure with Windows Server 2008. I'm using Google Chrome browser and it's showing the error below: GET 404 (Not Fo ...

What is the process of Defining an Element Based on Two Attributes in C#?

Is it feasible to specify a web page element based on two attributes? For example, I can locate the element by its innertext Element imagePage = ActiveBrowser.Find.ByContent(pageNumbers[p],FindContentType.InnerText); Alternatively, I can identify an ele ...

Create a music player application using the React context API

Here is a code snippet for implementing a music player using context: import React from 'react'; import { BarSongTitle, BottomBar, Button, PlayList, Song, SongTitle, } from './styles.js'; import { songList } from './con ...

In JavaScript, the checkboxes in all columns of a table with over 200 rows can be set, but only the checkboxes in the rows

Seeking help to implement toggle buttons for checkboxes on a page with a large table fetched from an external system. The table can have over 200 rows or more. Currently, I am facing an issue where I can only access and manipulate the visible checkboxes o ...

"Created a persistent fullscreen overlay over the body content, complete with scroll bars

Can a fixed fullscreen division position:fixed; width:100%; height:100%; cover the entire body of a page, including scroll bars? I understand that setting the body to overflow:hidden; can achieve this, but I am facing an issue where I want the fullscreen ...

Creating a responsive design using Bootstrap4

Today, I made the switch to bootstrap4 and enabled flexbox in _variables.scss. However, I'm still confused about the flexbox capabilities of bootstrap4. Some questions I have include: How can I utilize flex-direction:column? Is it possible to creat ...

Sharing configurations between a Node.js application and client-side JavaScript

I am facing an issue where I need to use a config object in both my node app and browser. Below is the path and content of the configuration file: path: [app]/public/js/config.js content: var config = { "foo": "bar", "num": 42, "list": ["a" ...

I am looking to serve static HTML files in Express.js while also retaining app.get() methods for handling server-side logic

It may sound trivial, but I am struggling with displaying HTML files within app.get() methods using Express. Most solutions I have found involve using app.use(express.static(__dirname + '/public'));, which limits server-side logic. What I want i ...

Error in Next.js 13 due to Prisma table mapping causing hydration issues

I recently created a basic project in Next.js 13 and encountered a Hydration Error even though my project is not doing much. The code snippet below seems to be the cause of the issue: import { PrismaClient } from "@prisma/client"; export default ...

The issue arises when AngularJS binding to a JSON object results in the value being

I am encountering a complex problem with nested bindings in custom directives. The JSON structure I am working with resembles the following; { survey: questions:[ { text:'Question 1', answers:[ { ...

Ways to implement a custom scrollbar across an entire webpage:

I am trying to implement the Jquery custom content scroller on my webpage to replace the default scrollbar. However, I am facing difficulties in getting it to work properly. You can view my code on Codepen. Although the plugin works fine with smaller blo ...

Acquiring JSON data through the use of jquery and php

Below is the HTML code I am working with: <div id="myDiv"> <p class="readMore"></p> <p class="readMore"></p> <p class="readMore"></p> </div> This is the jQuery function I am using: UPDATE <script> ...

Angular: Built-in solution for managing unhandled HTTP errors

I have implemented a default handler for handling http errors in my angularjs app as shown below: myapp.config([ '$httpProvider', function($httpProvider) { $httpProvider.responseInterceptors.push('errorInterceptor') }]) The errorI ...

Leveraging Javascript Variable in Kendo Grid Template

Creating two variables through an ajax call, their values remain constant after the page loads. var approvalLevel; var fullName; $(function() { $.ajax({ type: "GET", async: "false", url: approvalLevelURL, contentType: ...

vue-dropzone fails to create thumbnails when a file is added

I am facing an issue where I want to upload files that are already stored on my server to the Dropzone. Despite searching extensively through both vue-dropzone and regular dropzone documentation, as well as various GitHub issues for solutions, I have not b ...

What is the method for sending an AJAX request with a dynamically looping ID number parameter in the URL

I am looking to make multiple AJAX calls with a loop parameter named [id] in the URL, starting from request.php?id=1 and ending at id=9. I want to send each call after a 3-second delay. As a JavaScript beginner, I'm unsure of where to begin implementi ...

How to position div elements in the center on screens smaller than 768px?

Issue: Facing trouble centering my product grid under 576px. Question: How can I adjust the CSS to ensure the products are centered under 576px? My goal is to have the products centered when the screen size is under 768px, particularly for mobile devices ...

How to implement variables within the .map() function in JavaScript?

I am working on a map function where I need to pass in a variable as a Key to change the object item key to be based on that variable instead. For example, I want the obj.Salary below to actually represent the salary value when day equals "Day" instead o ...

Tips for resolving CORS error in swagger-ui-express

I'm encountering a "Possible cross-origin (CORS) issue?" error with Spec2 while running this swagger-ui-express application: const express = require('express'); var cors = require('cors'); const app = express(); const swaggerUi = ...