Choose a particular button using JavaScript and AJAX

In my Django app, users can save different items to a list. Each item has a corresponding delete button next to it.

Currently, when I click on any delete button, it always selects and deletes the first item in the list. This is because my JavaScript code uses the `var.product` selector which returns the value of the first element with the class name `.substitut`. I've tried using `$(this)` but haven't been successful.

How can I ensure that each delete button only targets and deletes its corresponding product?

This is an excerpt from my HTML:

   {% extends 'finder/base.html' %}
{% block content %}

<header class="masthead" id='fav_list'>
  <div class="col-lg-12">
    ...
  </div>

  <div class="w-75 mx-auto container-fluid" style='background-color: transparent;'>
    {% for saved in saved_list %}
      <div class='row d-flex justify-content-between'>
        ...
        <form class="form_id" method='post'>
          <button class='btn substitut' value='{{ saved.id }}'><i class='fas fa-trash-alt'></i></button>
        </form>
        ...
      </div>
    {% endfor %}
  </div>
...

This is an excerpt from my AJAX script:

$(".form_id").on('submit', function(event) {
    event.preventDefault();  
    var product = $(this).find('.substitut').val();         
    console.log(product);
    var url = '/register/delete/';   
    $.ajax({
        ...
    }); 
});

Answer №1

You have the option to utilize the onclick event in jQuery instead of using submit. This is because, based on the provided code snippet, it seems that you are not submitting your form directly. Instead, you are employing Ajax within your submit event, so making this adjustment should suffice. Modify your Ajax code as shown below:

$(".substitut").on('click', function(event) {
    event.preventDefault(); 
    //fetching the current button value that was clicked
    var product = $(this).val();         
    console.log(product);
    var url = '/register/delete/';   
   //insert your Ajax code here
});

Sample code :

$(".substitut").on('click', function(event) {
    event.preventDefault(); 
    //fetching the current button value that was clicked
    var product = $(this).val();         
    console.log(product);
    var url = '/register/delete/';   
   //insert your Ajax code here
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='substitut' value='{{ saved.id}}'><i class='fas fa-trash'></i></button>
<button class='substitut' value='{{ saved.id1}}'><i class='fas fa-trash'></i></button>
<button class='substitut' value='{{ saved.id2}}'><i class='fas fa-trash'></i></button>

Update 1: An alternative solution would involve creating a click event on the button to store the reference of the currently clicked button and then use it within your submit event.

Sample code :

var $submit = null;
var $button = $('button');

$(".form_id").on('submit', function(event) {
  event.preventDefault();
  //fetching the value of the clicked button
  var product = $submit.value;
  console.log(product);
  var url = '/register/delete/';
  $.ajax({
    url: url,
    type: "POST",
    data: {
      'product': product,
      'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
    },
    datatype: 'json',
    success: function(data) {
      if (data['success'])
        console.log(product);
      $("#fav_list").load(location.href + " #fav_list > *");

    }
  });
});

//when button is clicked
$button.click(function(event) {
  //storing the reference of the current button clicked in the variable $submit
  $submit = this;
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form_id" method='post'>{% csrf_token %}{{ saved.id}}
  <button class='substitut' value='{{ saved.id}}'><i class='fas fa-trash'></i></button>
</form>
<form class="form_id" method='post'>{% csrf_token %}{{ saved.id1}}
  <button class='substitut' value='{{ saved.id1}}'><i class='fas fa-trash'></i></button>
</form>

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

Struggling to retrieve error messages for empty or required fields while utilizing the Joi npm package

Joi package Version: ^17.6.0 I'm attempting to retrieve error messages for an array of object keys. See the Joi Validation Reference Image below: JSON Data: In the reference image, I have successfully validated most of the fields using Joi. However ...

Creating rows dynamically in an HTML table using JavaScript

Seeking assistance with creating a dynamic html table that can add a new row each time a user clicks on a specific link. The table is meant for filling in job details for different positions. Any help with the HTML code implementation would be greatly appr ...

How can I use MongoDB updateOne to retrieve the newest document instead of the oldest one?

Apologies for the elementary question, but I am determined to make this code function properly. When using the .updateOne() function in node.js to update my mongo database, I leave the parameters blank thinking it would update the most recently added docu ...

When I use Ajax to update my HTML, it causes Javascript to malfunction

Encountering an issue with a web application I've been developing recently, specifically related to ajax reloading causing javascript to fail. The following Ajax Call is in place $.ajax({ type: "POST", url: "/sortByI ...

Troubleshooting ES Lint Issue: Passing Parameters to a Vue Method

I'm encountering an ES Lint Parsing Error in my Vue page due to a syntax issue. The problem seems to be arising from a parameter in my method that contains a dot symbol. Error - Syntax Error: Unexpected token (1:1628) <div class="text-sm ...

What is the solution for the error message 'Uncaught SyntaxError: Unexpected token import'?

I've been struggling to troubleshoot this issue as I have not been successful in resolving it. Most of the solutions I came across mention configuring Babel correctly, but I am confident that I have already done so. My project utilizes Webpack for imp ...

A guide to creating a PHP/AJAX script that displays text based on the functionality of the PHP script

I am currently working on a script that involves an ajax call to another php file to retrieve data from an api. The api script consists of three different functions. When the ajax call is made, I want it to display a loading image and specific text based o ...

Testing a cucumber scenario by comparing the redirect URL with a different URL

Currently, I am working on writing Cucumber tests for my project. One issue I have encountered is that when clicking a certain button in my code, it redirects to another page with a fixed URL. How can I retrieve the current URL within the Cucumber test? I ...

Can I use Javascript to make changes to data stored in my SQL database?

I am delving into the realm of SQL and Javascript, aiming to insert my variable ("Val_Points from javascript") into a table ("Usuarios") associated with a specific user (e.g., Robert). Is it possible to achieve this using JavaScript, or are there alternati ...

Troubleshooting problem with infinite scrolling in AngularJS with Ionic framework

I recently created a webpage with an infinite scroll page load more script using Ionic AngularJS. However, I encountered an issue where the page restarts from the beginning once it reaches the bottom. Below is the HTML code snippet: <ion-content class ...

JavaScript code that opens a URL in a new tab with proper formatting

I'm having trouble figuring out how to make my JavaScript open a URL in a new tab. Here is the script: function viewSource(){ var webcache = "http://webcache.googleusercontent.com/search?q=cache:"; var request = "&prmd=ivn&strip=0& ...

A comprehensive guide on making an AJAX call to a self-hosted servlet

I created a servlet in Eclipse IDE for Java EE that posts data as an XML page and hosted it on a Tomcat server. The servlet can be accessed at http://localhost:8080/Checkers/CheckersServlet. When I open this URL in Firefox, the XML loads correctly. Now, I& ...

Issue with downloading files in Internet Explorer is not functioning properly

I am encountering an issue in my Angular.js controller where downloading a CSV file works perfectly in Chrome but not in IE. The browser console log indicates: HTML7007: One or more blob URLs were revoked by closing the blob for which they were create ...

Failed attempt to perform Ajax requests for REST API data

I am currently working on developing an application that requires a login through a REST API to retrieve a session id. To achieve this, I have set up a button that triggers a JavaScript function for making an AJAX call to authenticate the user. The result ...

Utilizing Varnish Cache to optimize AJAX GET requests

I am currently dealing with an AJAX request that is running on a server equipped with Varnish. The specific request is structured as follows: (function() { $("#name").autocomplete({ minLength:3, //minimum length of characters for t ...

When running `python manage.py makemigrations`, some fields may not be created properly by Django

While executing python manage.py makemigrations, I noticed that Django is not generating all the fields for the Todo model. Can someone please assist in identifying the issue? class Todo(models.Model): task = models.CharField(max_length=255) titl ...

Error message retrieval in Liferay fails due to malfunctioning Ajax listener

While working on a project using liferay jsf, I encountered an issue with inserting <f:ajax listener="#{jsfController.searchValidDestination}"> within <h:selectOneMenu/> in my view page. The problem is that I am not getting any result from the ...

Utilize array.map() or array.reduce() to generate a chart array

Presenting an array: this.dataArray = [ { id: 12, status: 2, number: 10 }, { id: 2, status: 2, number: 300 }, { id: 2, status: 2, number: 12 }, { id: 4, status: 2, number: 65 }, { id: 6, status: 2, number: 129 }, { id: ...

unable to locate text within tag a using javascript

I developed JavaScript code to search for tags within an accordion. function tagSearch(){ let keyword = document.getElementById('find').value.toUpperCase(); let items = document.querySelectorAll('.accordion'); let links = document ...

What are some ways to style an image that has been added using JavaScript using CSS?

I utilized a JavaScript function to add an image, which looked like this: function show_image(src) { var img = document.createElement("img"); img.src= src; document.body.appendChild(img); } But when I attempt to change its style using CSS: img ...