Despite having empty required fields, my form still manages to submit successfully

I'm encountering an issue with the form on my webpage. It transitions to show a thank you picture, but even though all inputs are required, the transition still happens if not every field is filled out.

My suspicion is that the problem lies with using an input element with type="image". When I switch to a regular button element, the transition only occurs when all fields are completed.

Additional information: The form functions correctly on the backend, it just shouldn't trigger the change unless all inputs are populated.

HTML (form)

<form id="form" action="/" method="POST">
    <div>
        <div class="inputName">
            <label for="name">Name</label>
            <input class="input" type="text" id="name" name="name" required>
        </div>

        <div class="inputEmail">
            <label for="email">Email</label>
            <input class="input" type="text" id="email" name="email" required>
        </div>
    </div>

    <div>
        <div class="inputSubject">
            <label for="subject">Subject</label>
            <input class="input" type="text" id="subject" name="subject" required>
        </div>
    </div>

    <textarea name="message" id="text" cols="30" rows="10" required></textarea>

    <input type="image" id="send" src='https://i.imgur.com/Tt39rjV.png' onmouseover="this.src='https://i.imgur.com/81fmcHg.png';" onmouseout="this.src='https://i.imgur.com/Tt39rjV.png';" border="0" alt="Send" />
</form>

EDIT: It's worth mentioning my JavaScript/jQuery code responsible for the fading effect:

$('#message').click(function(e){    
    $('.contact1').fadeOut('slow', function(){
        $('.contact2').fadeIn('slow');
    });
});

$('#send').click(function(e){    
    $('.contact2').fadeOut('slow', function(){
        $('.contact3').fadeIn('slow');
    });
});

Answer №1

It seems that the issue arises from using an input element with type="image". In contrast, when utilizing a regular button element, the fade effect only occurs after all necessary fields are filled out.

This emphasizes the importance of taking charge of validation on your own. Instead of using <input type="image">, opt for a button with type="submit" and embed your image within it. Additionally, connect your fade logic to the form's submit event rather than just the click event.

<input type="image"> is primarily designed for cases where click coordinates need to be captured.

form.addEventListener("submit", e => {
   e.target.textContent = "Submitted!";
   e.preventDefault();
});
<form id="form" action="/" method="POST">
    <div>
        <div class="inputName">
            <label for="name">Name</label>
            <input class="input" type="text" id="name" name="name" required>
        </div>

        <div class="inputEmail">
            <label for="email">Email</label>
            <input class="input" type="text" id="email" name="email" required>
        </div>
    </div>

    <div>
        <div class="inputSubject">
            <label for="subject">Subject</label>
            <input class="input" type="text" id="subject" name="subject" required>
        </div>
    </div>

    <textarea name="message" id="text" cols="30" rows="10" required></textarea>

    <button type="submit">
       <img style="width: 20px" src='https://i.imgur.com/Tt39rjV.png' onmouseover="this.src='https://i.imgur.com/81fmcHg.png';" onmouseout="this.src='https://i.imgur.com/Tt39rjV.png';"/>
    </button>
</form>

(In addition, I firmly believe that jQuery should never be relied upon.)

Answer №2

Consider using this snippet:

1. Assign the ID "txtBox" to the required textbox and utilize the following script-

$(function(){
$("#my-form").validate();
});

$(function(){
if($("#txtBox").val() != ""){
$('form[name="required-form"]').submit(function(event){
    $('#required-form').fadeOut("slow", function () {
    $('#optional-form').fadeIn("slow");
}
else{alert('Please ensure all mandatory fields are completed');}
});

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

From jQuery to Vanilla JavaScript: Implementing a simple click event listener

I've been attempting to translate the following jQuery code into vanilla JavaScript, however, I can't get it to function properly. jQuery: $(document).ready(function() { $("button").click(function() { var char = "0123456789abcdefghijklmno ...

Encrypt/decrypt ajax URL in Laravel

Code Snippet: public function searchAjax(Request $request) { if ($request->ajax()) { $output = ""; $productIndex = Product::where('product_name', 'LIKE', '%' . $request->states . &apo ...

Developing a method to handle HTTP errors when utilizing the fetch method to retrieve data from an API endpoint

// GitHub users document.getElementById('btn3').addEventListener('click', fetchData); // Fetching from external API function fetchData() { fetch('https://api.github.com/users') .then(function (res) { co ...

Does JavaScript adhere to a particular pattern?

Is there a more streamlined approach to implementing this particular design pattern? function a() { function x() { /* code */ } function y() { /* code */ } /* additional code */ x(); y(); // can be called from here } a(); a.x(); a.y(); I ...

Executing a function within a series of module.exports calls in Node.js

In my coding journey, I encountered a puzzling scenario. I defined a function in one model called review and exported it for other files to utilize in the usual node fashion. Then, I made reference to this function in another model named company and export ...

Experience running two functions simultaneously in jQuery simulation

Presented here are two functions that I am working with: loadTop(); loadBottom(); One of these functions is responsible for loading the top portion of a page while the other takes care of loading the bottom. The loadTop function involves asynchronous o ...

Proceed once all .load() functions have been completed

I am encountering an issue with an asynchronous JavaScript function. I currently have a function that is inserting elements one by one, which is functioning correctly. However, my goal is to proceed only after all the .load() functions have completed. The ...

Trouble arises when attempting to compare two JSON files with an undefined issue

data-info.json {"price-comparison":[[{"Price":"0.0"},{"Code":"C0358102"}],[{"Price":"2.0"},{"Code":"C0876548"}]],"isEmployeeOJ":"Y"} script.js var dataInfo = $http.get("data/data-info.json").then(function (response) { $scope.dataInfo = response.data; ...

Utilizing function arguments to retrieve values in JavaScript within the framework of CodeIgniter

I'm having an issue in my Ajax code where the values are not being stored in the items variable even though they are properly fetched and assigned to the values variable. Can anyone spot what I might be doing wrong? Specifically, within the onload fu ...

The eternal dilemma: async with axios or simply axios, which will you choose?

Is there a difference between these two useEffect functions? useEffect(()=>{ async function fetchData(){ await axios .get(path, config) .then(resp=>console.log(resp)) .catch(error=>console.log(error)) } fetchData(); },[ ...

Modify the HTML select tag to toggle from a selected checkbox

What should I do when a certain option is checked in the checkbox, and that label needs to be shown in the select tag? https://i.stack.imgur.com/ZxRNF.png Checkbox input <input type="checkbox" class="toggle-product pull-right" @if(!isset($restrictedPr ...

Exploring the possibilities of integrating React Suspense with react-router-dom

I've been exploring lazy loading in my projects to implement lazy loading routes with react-router-dom. I came across two methods while researching online - wrapping all routes with a single React.Suspense or putting each page within its own React.Sus ...

What steps can I take to avoid errors triggered by clicking on an element that is unresponsive on the page?

While creating a test for an element on the page, I encountered an issue. Everytime I utilize the command pageObject.click("@MyElement"), there are instances where it produces this error message: Element <i class="...">...</i> is not ...

I must convert this option into a checkbox

I am facing a challenge with this task, where I need to convert a select form into a checkbox form. Although I have managed to change the visuals, the functionality of the checkboxes does not match that of the select form. Below is the original select for ...

utilizing callback function for creating shopping cart feature within React

I'm in the process of creating an ecommerce website and implementing the add to cart functionality. I'm facing an issue where passing a callback function using props from a component to the parent component isn't working as expected. I' ...

`Discover the latest version of Tailwind using JavaScript or PHP`

My setup includes Laravel v8.81.0 (PHP v8.1.2), Vue v3.2.30, and Tailwind https://i.sstatic.net/fVbJB.png I am looking to fetch the Tailwind version in JavaScript similar to how I can get the Vue version using: //app.js require('./bootstrap'); ...

When a list item is clicked, extract its innerHTML and pass it to a JavaScript

Hey there, I've created a basic HTML/JavaScript calculator. Each time I perform a calculation, it gets added to the list shown on the webpage. Here's what I'm looking for: When a user clicks on an item in the list, I want to retrieve the s ...

Increase the activity in every inquiry

In my Node.js application, I have a file with the following contents: index.js contents: var app = require('express')(); var http = require('http').Server(app); function start(){ var timer = setTimeout(function(){ check() ...

Issue: Error message - Unhandled promise rejection: NodeInjector error - ControlContainer not found

I'm having trouble validating a form and encountering an error. I tried implementing the suggestions provided in the following threads without success: Getting error suddenly in Angular Error: NodeInjector: NOT_FOUND [ControlContainer] Using forms i ...

What is the reason behind tags being closed automatically?

When I use $("#ID").html("<p><div></div><span></p>");, the output appears as follows: <div id="ID"> <p><div></div><span></span></p> </div> The span tag is automatically closed ...