JavaScript form validation eliminates input data

I recently started using the JavaScript library for client-side form validation called Bouncer. It has been working really well, but I have encountered a peculiar behavior that I need help understanding.

My form has two submit buttons with different values. When I don't validate the form using the library, I can retrieve the exact button value on the server-side. However, when I implement the library for validation, the button value disappears. All other form values remain accessible. Upon inspecting the library code, I noticed that the line "event.preventDefault()" seems to be causing this issue.

If I remove this line, everything works as expected, but unfortunately, the form validation will no longer function properly.

Does anyone have any insights or suggestions on how to resolve this? Any help would be greatly appreciated!

var submitHandler = function (event) {

            // Only run on matching elements
            if (!event.target.matches(selector)) return;

            // Prevent form submission
            event.preventDefault();

            // Validate each field
            var errors = publicAPIs.validateAll(event.target);

            // If there are errors, focus on the first one
            if (errors.length > 0) {
                errors[0].focus();
                emitEvent(event.target, 'bouncerFormInvalid', {errors: errors});
                return;
            }

            // Otherwise, submit if not disabled
            if (!settings.disableSubmit) {
                event.target.submit();
            }

            // Emit custom event
            if (settings.emitEvents) {
                emitEvent(event.target, 'bouncerFormValid');
            }

        };
<button class="" name="page[__page]" type="submit" value="0">back</button>
<button class="" name="page[__page]" type="submit" value="2">next</button>

Answer №1

It appears that the problem arises when using the standard method of submitting forms, as the submitter is not properly handled with the .submit() function:

If any of the following conditions are met:

  • The element is a button that is not designated as the submitter.

Then proceed.

To address this issue, it seems like moving this information into a hidden field and utilizing the real submitter (either next or prev) to populate its value would be an effective solution.

For instance

document.body.innerHTML = `
  <form>
    <input type="hidden" name="page[__page]">
    <button class="" type="submit" value="0">back</button>
    <button class="" type="submit" value="2">next</button>
  </form>
`;

document.body.firstElementChild.addEventListener('submit', e => {
  e.preventDefault();
  var page = e.target.querySelector('input[name="page[__page]"]');
  page.value = e.submitter.value;
  e.target.submit();
});

By making these adjustments, the form submission process should now work correctly, resolving your initial concern.

Additionally, you may want to consider exploring form.repostValidity() and utilize e.preventDefault() only if the report comes back as false.

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

Troubleshooting npm installation issues on Ubuntu 18.04

While attempting to set up Hooper for a Vue.js example, I used the command: $ npm install hooper This resulted in the following error message: npm ERR! file /home/juanlh/package.json npm ERR! code EJSONPARSE npm ERR! JSON.parse Failed to parse json npm ...

When only showing the title to the client, it results in an undefined value

I have created a schema in mongoosejs that looks like this: var uploadSchema = mongoose.Schema({ title : String, happy : String, }); I am trying to show the data from my database on the client side (using ejs for templating) ...

Ways to retrieve the current URL in Next.js without relying on window.location.href or React Router

Is there a way to fetch the current URL in Next.js without relying on window.location.href or React Router? const parse = require("url-parse"); parse("hostname", {}); console.log(parse.href); ...

Convert this JavaScript function into a jQuery function

I currently have this JavaScript function: function removeStyle(parent){ var rmStyle = document.getElementById(parent).getElementsByTagName("a"); for (i=0; i<rmStyle.length; i++){ rmStyle[i].className = ""; } } Since I am now using ...

What is the process for setting %20 to represent a space in URL parameters?

I am currently working on developing an android application that involves sending data to the server side using GPRS and SMS (via an SMS gateway). The challenge I am facing is with formatting the data before sending it to the SMS gateway. The format provid ...

Upon page load, a dazzling SVG file will flicker before being adorned with CSS styles

I'm experiencing an issue with an SVG arrow icon on my webpage that flashes quickly across the entire screen upon page load before settling into its proper size and placement. I've tried using CSS to initially hide the icon and then reveal it aft ...

Vue .filter doesn't work with reactive data sources

I'm currently working on a project that involves creating a dynamic shipping estimate in a Shopping Cart. The challenge I face is retrieving shipping methods from an API endpoint and making the data reactive to update in real-time based on the selecte ...

Problem with Java class in GWT JsInterop

Having some trouble with JsInterop while wrapping up a piece of JavaScript code. The JavaScript code looks like this: com = { gwidgets: {} }; com.gwidgets.Spring = function () { this.name = "hello"; }; com.gwidgets.Spring.prototype.getName = ...

CSS struggles after implementing conditional checks in return statement for an unordered list

I'm encountering a CSS issue with the header section. When I include the following code snippet in my code to display a tab based on a condition, the entire header list doesn't appear in a single horizontal line: <div> {isAdmin(user) ? ...

Error loading resource: The server returned a 404 status code indicating the requested resource was not found in the Node.js socket.io

My challenge involves setting up a server with Node.js and socket.io which starts perfectly fine. However, when I attempt to access my server's site through the browser, it shows "Cannot Get /" and in the console, an error appears saying "Failed to Lo ...

Undefined output in Typescript recursion function

When working with the recursion function in TypeScript/JavaScript, I have encountered a tricky situation involving the 'this' context. Even though I attempted to use arrow functions to avoid context changes, I found that it still did not work as ...

Angular's FormGroup for reactive forms is a powerful feature that allows for

Why am I unable to type in the input field before setting a value? html <form action="" [formGroup]="titleForm"> <input class="note-title" type="text" formControlName="title"> </form> ...

What are the steps to integrate npm into a Cordova app within Visual Studio?

I am currently working on developing a hybrid app using the "Tools for Apache Cordova" project template in Visual Studio. To incorporate angular2 into my project, I have added all the necessary modules to packages.json. After compiling everything and reso ...

Prevent onClick event in jQuery and extract parameters from a function call

We've been tasked with implementing a temporary solution to some code, so it might seem a bit silly at first. But please bear with us. The goal is to block the onclick method of an anchor tag, extract the parameters from the function call, and then u ...

Seamless Integration of jQuery Functions

I am in need of some assistance with passing a chain of jQuery methods into a function as an argument. The goal is to have dynamic methods executed on a DOM object. This functionality would be particularly useful for writing qUnit tests where centralizat ...

Displaying Stats.js inside a different canvas using ThreeJS

Just starting out with Three.js and wanted to test displaying the Stats.js in a small scenario. Check it out here Decided not to use modules for now, but followed similar code structure as in the examples: var stats = new Stats(); var renderer = ...

What is the best approach to detect multiple .change() events on elements that are dynamically updated through AJAX interactions?

Here is my first question, and I will make sure to follow all the guidelines. In a PHP page, I have two select groups, with the second group initially disabled. The first select group is named "yearlist", while the second select group is named "makelist" ...

Utilizing the Power of Mui Datatable to Enhance User Experience with Repeatable Edit and Delete

Hey Everyone, I'm currently trying to implement edit and delete buttons in ReactJS using Mui Datatable. However, I am facing a recurring issue due to the Map function since I am relatively new to ReactJS. Below is my image and code snippet: Here is a ...

Position the column content to the right side of the cell using React MUIDataTable

I'm a beginner with MUI and I need assistance aligning the content of a column to the right. Here is my code snippet: <MUIDataTable title={""} data={data || []} columns={realColumns ? realColumns(data, modeMO) : columns(data, modeMO ...

Customize.Print - establish default print preferences

In my current project, I am exploring ways to add a print PDF feature. After discovering print.js, it seems like a possible solution for this task. My main concern is setting default print options to ensure the correct scale (i.e., 100%). Does print.js h ...