Expanding the capabilities of the JQuery submit function

Within my web application, I find myself working with several forms, each possessing its own unique id. To streamline the process, I decided to create a custom handler for the submit event in my JavaScript file:

$('#form-name').submit(function(event) {
    event.preventDefault();
    const formData = new FormData($('#form-name')[0]);
    const json = JSON.stringify(Object.fromEntries(formData));
    ws.send(json);
});

The objective is to avoid duplicating this code for every form. Initially, I wrapped it within another function like so:

function custom_submit(form, event) {
    event.preventDefault();
    const formData = new FormData($(form)[0]);
    const json = JSON.stringify(Object.fromEntries(formData));
    ws.send(json);
}

Subsequently, I aimed to utilize it by calling:

$('#form-name').submit(custom_submit('#form-name', event));

This approach encountered syntax errors and still necessitated manually connecting each individual form to the custom function.

Is there a method to link all forms sharing a specific prefix to my custom submit function, while automatically passing both the form's id and the event variable? Consider a prefix such as:

form-ws-*

Answer №1

$('form').on('submit', function(event) {
    event.preventDefault();
    const data = new FormData(this);
    const jsonData = JSON.stringify(Object.fromEntries(data));
    ws.send(jsonData);
}); 

is responsible for managing forms across the entire webpage

Answer №2

To optimize form submission, consider creating a custom jQuery plugin and attaching it to the desired forms using any jQuery selector.

Step-by-step usage:

$("<SELECTOR>").submitify();

(function($) {
  $.fn.submitify = function() {
    var $this = $(this);
    $this.on('submit', function(event) {
      event.preventDefault();
      const formData = new FormData(this);
      const json = JSON.stringify(Object.fromEntries(formData));
      console.log(json);
      //ws.send(json);
    });
    return this;
  };
}(jQuery));

$(document).ready(function() {
  $('[id^=form-ws-]').submitify();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <form id="form-ws-f1" class="col-md-4">
      <input type="text" class="form-control" name="t1" id="t1" />
      <input type="submit" value="submit" />
    </form>
    <form id="form-ws-f2" class="col-md-4">
      <input type="text" class="form-control" name="t2" id="t2" />
      <input type="submit" value="submit" />
    </form>
    <form id="form-ws-f3" class="frm col-md-4">
      <input type="text" class="form-control" name="t3" id="t4" />
      <input type="submit" value="submit" />
    </form>
  </div>
</div>

Access the interactive JsFiddle demo here: https://jsfiddle.net/nitinjs/650guLhr/15/

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

Is it possible to create a development build using Npm with React and Typescript?

I have successfully set up a TypeScript React app by using the command below: npx create-react-app my-app --template typescript However, running "npm start" generates development javascript files and launches a development server which is not id ...

Managing loading and changing events using Angular, jQuery, and Web API

I am populating a dropdown select using ng-repeat. <select onchange="ChangeMonth()" id="month"> <option ng-repeat="(key,val) in Months" ng-selected="val==ActiveMonth" value="{{key}}"> {{val}} ...

pnpm may not be able to resolve dependencies

When I have my package.json file and install all dependencies with npm i, everything works fine. However, when I use pnpm i, I encounter an exception: TypeError: Cannot read property 'uid' of undefined. I don't actually use this library, so ...

The ng-click functionality seems to be malfunctioning when used within the controller in conjunction with ng-bind

After coding, I noticed that my ng-click function is not working. When I inspected the element, I couldn't find ng-click displayed anywhere. Can someone please help me figure out what I'm doing wrong? var app = angular.module('myApp' ...

Extracting data on an AngularJS platform by using web scraping techniques

I have been working on an AngularJS application that currently retrieves JSON data from an API using http.get, and it's been working really well. Recently, I've been exploring the idea of passing a URL to a static webpage and scraping the result ...

Recording JavaScript Cookie Visit Counts and Tracking Last Login Dates

I am a beginner in JavaScript and cookies, and I am attempting to create a cookie that can show the number of times someone has visited a website, the date of their last visit, and the expiration date of the cookie. Initially, I tried modifying code from ...

Develop a descriptive box for a radio button form using jQuery

I am working on creating a form with simple yes/no questions. If the answer is no, no explanation is needed. However, if the answer is yes, I want to insert a new table row and display a textarea for an explanation. To ensure data validation, I am utilizi ...

The second parameter of the filter function is malfunctioning

I'm currently delving into the "filter" function in AngularJS. Upon reviewing the documentation, I've discovered that it can also take a second parameter. When set to "true", it carries out a strict comparison. HTML <fieldset> <leg ...

Unable to transfer data through Ionic popover

I've encountered an issue when trying to pass data to my popover component, as the data doesn't seem to be sent successfully. Code HTML <div class="message" id="conversation" *ngFor="let message of messages.notes"> <ion-row class= ...

Send data from an AJAX request to a Laravel controller

Here is the code for my ajax request where I am trying to pass values to a controller in Laravel. var deviceid="<?php echo $id; ?>"; var day="<?php echo $day; ?>"; $.ajax({ 'async': false, 'global': false, url ...

How to correctly serialize nested maps in JQuery ajax data for sending?

var locationData = { "location" : { "name" : $("#user_loc_name").val(), "street_address" : $("#user_loc_street_address").val(), "city" : $("#user_loc_city").val(), "province" : ...

Issues with logging functionality in my React Native application

I am currently facing an issue with my React Native app running on the Android Studio emulator. The logging does not appear in my terminal or in the active remote debugger in Chrome when debugging is enabled. When I attempt to log a simple text in one of m ...

Issue: Unable to locate the module 'babel-code-frame' in VUEJS (ESLINT)

Here are the current versions: -npm: 6.14.4 -node: v10.19.0 -eslint: v5.0.1 -linux: ubuntu 20.04 This is my script: vue create vue1 cd vue1 npm run serve This is my package.json: { "name": "vue1", "version": "0. ...

Is there a way to handle the ajax request only when necessary, instead of processing it every few seconds?

Currently, I am working on an AJAX chat system using PHP, MySQL, JavaScript, and AJAX. I have a piece of code that retrieves all chat messages within a div using AJAX, with the function running every 2 seconds. My issue lies in the fact that the div autom ...

Identifying Flash content in a unique way

In my dynamic page (let's call it myFlashContainer.jsp), the Flash content changes based on the link that is clicked. The code responsible for rendering the Flash looks like this: <object height="100%" align="l" width="100%" id="player" codebase= ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

The size of objects on canvas is not consistent when loading with fabric.js loadFromJSON

Click here to view the code var canvas = new fabric.Canvas('canvas_1'); var canvas2 = new fabric.Canvas('canvas_2'); var imgObj = new Image(); imgObj.src = "https://gtaprinting.ca/wp-content/uploads/2021/05/blank-t-shirt-front-gre ...

Formatting Date and Time in the Gridview of my Asp.net Application

I have been using this format to display the date and time in a grid. The issue I am facing is that I cannot retrieve the exact HH:MM from the database. Even though the database shows 11:11, my grid is displaying 11:03 instead. Here is the value stored in ...

Ways to verify the occurrence of a successful event following the execution of a save() operation on a model

Below is the snippet of code I am using to store extra properties in a model (specifically, the answer model) selectMedia: => # Post media to server @options.answer.id = @options.answer.get('_id') @options.answer.url = "/v1/answers/#{@o ...

Enhance your online shopping experience with a personalized touch by incorporating an Ajax add to cart button on

Currently, I am working on customizing the add to cart button on a single product page. After implementing an ajax call solution from LoicTheAztec's post here, I have successfully added the feature. The code works perfectly fine, but now I am faced w ...