If a submit event listener was added to the form, what will the event.target contain?

I am managing multiple forms on a single page, and upon submission of one form, I aim to send an AJAX request with specific data to the backend view. My goal is to identify if the clicked form matches the event target in order to proceed. I attempted the following approach, but I am unsure if it is correct (the first console.log works, but the second does not):

<div id = "list">
            {% for article in news %}
                <a href="{{ article.resource }}"><h1>{{ article.title }}</h1></a>
                <p>{{ article.published }}</p>
                <img src = "{{ article.url }}">
                <p>
                    <button><a href="#" class="vote" id="{{ article.id }}" action = "upvote">Upvote</a></button>
                    <button><a href="#" class="vote" id="{{ article.id }}" action = "downvote">Downvote</a></button>
                </p>
                <div id="span">
                    {% with article.upvotes.count as total_upvotes and article.downvotes.count as total_downvotes %}
                        <span upvote-id = "{{ article.id }}">{{ total_upvotes }}</span><span> upvote{{ total_votes|pluralize}}</span>
                        <span downvote-id = "{{ article.id }}">{{ total_downvotes }}</span><span> downvote{{ total_votes|pluralize}}</span>
                    {% endwith %}
                </div>
                <form method = 'post' action = '{% url "news:news_list" %}' form-id = '{{ article.id }}' class="form">
                    {{ form.as_p }}
                    {% csrf_token %}
                    <input type = "submit" value = "post">
                </form> 
            {% endfor %}
        </div>
{% endblock %}
{% block domready %}
        const 
            list = document.getElementById('list'),
            items = document.getElementsByClassName('vote');
            forms = document.getElementsByClassName('form');

        list.addEventListener('click', voteFunc);
        list.addEventListener('submit', commentFunc);

        function commentFunc(event){
            event.preventDefault();
            const clickedForm = event.target;
            console.log('event triggered');
            for (let form in forms){
                if (form == clickedForm){
                    console.log('form is event.target')
                    $.ajax({
                        url: '{% url "news:news_list" %}',
                        type: 'POST',
                        data: {'id':$(event.target).attr('form-id'), 'title':$(this).elemets['title_field'].text(), 'body':$(this).elemets['body_field'].text()}, 
                        dataType: 'json'
                    })
                }
            }
        }

Seeking advice on improving implementation and understanding the contents of event.target.

Answer №1

To handle the form submit event, create an event handler. This event will be triggered when the submit button (post) is clicked. Utilize the .serialize() method to gather all inputs within the form. Additionally, attach a form-id using &name=value, and then transmit this data to the backend.

Demo Code :

//when form will get submit
$("form.form").submit(function(e) {
  //serialize will get all inputs as name=value separted wth `& `
  console.log("data to send --> " + $(this).serialize() + "&id=" + $(this).attr('form-id'))
  $.ajax({
    type: "POST",
    url: '{% url "news:news_list" %}',
    data: $(this).serialize() + "&id=" + $(this).attr('form-id'), //send same
    dataType: 'json'
  });
  e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list">

  <a href="{{ article.resource }}">
    <h1>A1</h1>
  </a>
  <p>abcd..</p>
  <img src="{{ article.url }}">
  <p>
    <button><a href="#" class="vote" data-id="1" action = "upvote">Upvote</a></button>
    <button><a href="#" class="vote" data-id="1" action = "downvote">Downvote</a></button>
  </p>
  <div id="span">

    <span upvote-id="1">23</span><span> 54</span>
    <span downvote-id="1">2</span><span> 56</span>
  </div>
  <form method='post' action='{% url "news:news_list" %}' form-id='1' class="form">
    <p><label>somehting:</label>
      <input type="text" name="something"></p>
    <input type="submit" value="post">
  </form>

  <a href="{{ article.resource }}">
    <h1>A</h1>
  </a>
  <p>abcd..</p>
  <img src="{{ article.url }}">
  <p>
    <button><a href="#" class="vote" data-id="2" action = "upvote">Upvote</a></button>
    <button><a href="#" class="vote" data-id="2" action = "downvote">Downvote</a></button>
  </p>
  <div id="span">

    <span upvote-id="2">23</span><span> 54</span>
    <span downvote-id="2">2</span><span> 56</span>
  </div>
  <form method='post' action='{% url "news:news_list" %}' form-id='2' class="form">
    <p><label>somehting:</label>
      <input type="text" name="something"></p>
    <input type="submit" value="post">
  </form>
</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

Looking for a solution to the error message "React Native Splash Screen shows 'null is not an object

I have followed all the steps outlined in this guide: https://www.npmjs.com/package/react-native-splash-screen and also watched a YouTube tutorial covering the same process. Here is the code snippet that I have implemented: import * as React from 're ...

What is the best way to script a function that switches is_active from False to True?

Is there a way to create a function that switches is_active=False to True? I am looking to develop a function that can change the user status from is_active=False to is_active=True. Ultimately, my goal is to implement an "email verification" process for ne ...

Improving a lengthy TypeScript function through refactoring

Currently, I have this function that I am refactoring with the goal of making it more concise. For instance, by using a generic function. setSelectedSearchOptions(optionLabel: string) { //this.filterSection.reset(); this.selectedOption = optionLa ...

Generating dynamic choices in Django application

I'm facing an issue with populating choices in a Django form dynamically. The options are fetched from an external API. Here is my current model setup: from django.db import models class MyModel(models.Model): choice_field = models.CharField(max ...

Understanding conditional statements in JavaScript can greatly enhance your programming skills

Here's a search component that I've been working on. I'm trying to figure out how to handle the scenario where there are no items in the array. Should I use an if statement or is there another approach I should take? Any help would be greatl ...

Extracting information from a JSON data within an API

How can I retrieve data with a name tag from JSON data using Ajax? The function showCard is not functioning properly when I try to grab data with a name tag. My goal is to display the name of the API data when an img element with the class found is clicked ...

Sending data from Web Service to Ajax Request success callback function

Hello Coding Comrades, I am currently working on a form with a SSN textbox that triggers an ajax request to determine if an employee has been hired before. The data returned from the Web Method is in the form of a TermedEmployee Object, but I'm stru ...

Collect data from a third-party website that necessitates the activation of JavaScript

Given that phantomjs has been abandoned, I am exploring alternative methods. For instance, using chrome-webdriver may not be ideal as it cannot operate on a remote host like heroku. Is there a way to scrape a website that relies on JavaScript being activa ...

Creating an Ajax form for adding items in CakePHP view (related)

Currently, I am looking at a view of my client at http://localhost/client/view/3 where I can see his address in the related section. Cakephp has automatically set this up. If you click on the Add Address button, a new page opens up at http://localhost/adde ...

How can I confirm that all elements have been properly reset to their original positions prior to making any further adjustments to them?

In need of some creative brainstorming, I'm working on a website design featuring ten overlapping cards. When the mouse hovers over a card, it expands while others move away. My goal is for each card to return to its original position once the cursor ...

Struggling with passing parameters through a route and displaying them in the Reddit app using React?

I'm currently working on a project that involves displaying threads from various subreddits when a user clicks on a list item using routes and react. However, I've encountered some issues with getting the information to display correctly. Below i ...

Difficulty encountered while trying to access JSON object

I've been utilizing the LinkedIn JS API to retrieve a list of individuals. The data is returned in JSON format, and here is the callback function: .result(function (result) { profile = result.values[0]; // Perform an action with the f ...

I simply aim to remove a single piece of news at a time, yet somehow I manage to delete more than intended

Do you have a PHP file containing a list of news items fetched from the database? Each news item has a delete link, which looks like this: echo '<a id="'.$result_news['id_news'].'" class="j_newsdelete" href="#">Delete</a ...

Browser-agnostic script proxy

Currently, I am working on client-side Javascript which interacts with JSON web services from a different domain. I've learned that certain browsers don't permit cross-domain scripting, so it's recommended to set up a proxy on my local serve ...

Certain hues remain unaffected when changing themes, exclusive to Chrome

I have been working on a project that includes a toggle feature to switch between different themes. However, I am encountering an issue where the theme does not update properly when changing from a dark theme to a light theme or vice versa. The colors rema ...

Javascript function fails to run smoothly during rapidscrolling

I'm facing an issue with my JavaScript code that adjusts the transparency of the navigation bar while scrolling. It works perfectly when scrolling slowly, but when the scrolling speed is fast, it seems like the function is not triggered and the navbar ...

What is the reason FileReader does not transfer the file to loader.load() in the three.js scene?

Trying to utilize FileReader to send an ASCII file from the client side to loader.load() seems to be causing an issue. The file doesn't reach its destination. However, if I use loader.load('server path to test_file.stl') instead of loader.lo ...

Issues encountered when accessing django admin panel with superuser credentials

While writing code, everything was functioning correctly with all services running via docker-compose. However, the database unexpectedly crashed and I had to clean up the database files and recreate them using the same docker-compose setup. After recreati ...

Unable to display Three.JS OBJ Model

I am facing an issue with loading a .obj model in Three.js. I created the model in Cinema 4D, exported it with a scale of 1 meter, and tried to load it using OBJLoader in Three.js. However, even though there are no errors, the model is not showing up. Wh ...

A plug-in for TinyMCE that allows users to adjust column widths within a table

We utilize TinyMCE in our content management system (CMS), and our users have expressed interest in being able to adjust the width of a column within a table. While HTML technically does not recognize columns, the Moodle editor HTMLAREA includes a plugin t ...