Difficulties arising from displaying errors when submitting empty fields

I am facing an issue with my script - the problem arises when trying to display errors. The error message appears but does not function properly, causing a break after the submit button. Essentially, if the fields are empty, an error should be displayed, and while it does work in doing so, the display of the error seems to halt the process.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form method="post">
  <input type="text" id="text_field1" />
  <input type="text" id="text_field2">
  <button type="submit" id="submit_button">Submit</button>
  <button type="submit">Submit</button>
  <p id="error_resp"></p>
</form>
<script>
  $("#submit_button").click(function() {
    if ($("#text_field1").val() == "")
      $('#error_resp').text('please fill the required field');
    else if ($("#text_field2").val() == "")
      $('#error_resp').text('please fill the required field');
    else
      return true;
  });
</script>

Answer №1

Your form HTML has a few issues that need addressing.

  1. Make sure to use the preventDefault() method to prevent the default behavior of the form and enable input validation.
  2. Avoid checking for empty inputs using == "". Simply use ! to check if an input is empty and display the appropriate error message.
  3. When displaying errors in error_resp, consider using .html to clear previous messages and replace them with new ones.

For more information on .html, refer to this resource.

Execute the snippet below to see the changes in action:

$("#submit_button").click(function(e) {
  e.preventDefault();
  if (!$("#text_field1").val()) {
    $('#error_resp').html('please fill the first required field');
  } else if (!$("#text_field2").val()) {
    $('#error_resp').html('please fill the second required field');
  } else {
    $('#myForm').submit();
    console.log('All looking good. Form will submit now')
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="myForm" action="filename.php">
  <input type="text" id="text_field1" />
  <input type="text" id="text_field2">
  <button type="submit" id="submit_button">Submit</button>
  <p id="error_resp"></p>
</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

Mozilla Extension: Run code on initial launch

Currently in the process of building an add-on and looking to implement specific code for its initial run. What I aim to achieve is clicking on the add-on button, navigating through files, and selecting an executable file. This browsing action should only ...

Is the first child component of Material UI Stack not properly aligned?

Is there a CSS issue that needs fixing? I am working on creating a vertical list of checkboxes with labels using the <Stack /> component from Material UI. I have tried implementing this in the sandbox provided (check out demo.tsx): https://codesandb ...

Verifying input for Numeric TextField

The text field being used is: <TextField variant="outlined" margin="normal" id="freeSeats" name="freeSeats" helperText={touched.freeSeats ? errors.freeSeats : ''} error={touched.freeSeats && Boolean(errors.fre ...

Customizing Background Image Opacity in MuiCssBaseline

I recently tried to set a background image for my demo application built with React, Next, and Material-UI. In my _app.js file, I included the following code: import React from 'react'; import { ThemeProvider } from '@material-ui/core/styles ...

Alert: Parser error in JSONP!

$.ajax({ type: "GET", dataType: "jsonp", jsonpCallback: "jsoncallback", //async: true , data: { // some other data here }, url: "http://mywebsite.com/getRequest.php", success: function(response ...

jQuery Expander and Bulleted Lists

Recently, I decided to test out the jQuery expander plugin that I discovered here. While it works well with regular text, I noticed some odd behavior when the slice point falls in the middle of an <LI> tag. Are there any helpful tips or suggestions ...

Create a connection between two draggable boxes by drawing a line with Selenium WebDriver using Java programming

My current project involves working with Selenium Web Driver, however, my application does not support CSS selectors. Within the application, there is a Flowchart page where I am tasked with adding a FlowChart. This requires dragging and dropping two recta ...

Is it feasible to block indent the second line of a URL?

Is there a way to indent a second line of a URL so that it aligns perfectly with the first letter of the sentence? I attempted using <ul>, but encountered issues as it inherited small text and bullet points from the main .css file. Check out this li ...

Using a variable as a parameter in a jQuery function

After selecting multiple options from a dropdown menu, I intended to use these selections as filters for my table rows. However, the code snippet below is not producing the desired results: <select name="courier" class="selectpicker courierpicker" mult ...

Using a custom font in a Django project without relying on the Google Fonts API

I've hit a roadblock in my programming journey and I'm seeking help. As a newcomer to both programming and Django, I've been following a helpful tutorial up until part 4. Everything was going well until I stumbled upon a new font online cal ...

jQuery enables the toggling of child elements with a specific class (handlers) upon clicking

My goal is to change the style of a specific child element when I click on its parent. I was able to achieve this using event handlers: $(".p1").on({ mouseenter: mouseEnter, mouseleave: mouseLeave }); function mouseEnter() { $(this).css(&apos ...

When scrolling a semi-parallax effect in a resized window, I notice a calming presence of empty white

I recently acquired a WordPress website from its previous owner, and I'm encountering an issue with the parallax section at the top. It seems to be scrolling at a slightly slower pace than the rest of the page. I've tried adjusting the width and ...

Using Selenium in Java to interact with popup elements

Attempting to retrieve and interact with pop-up/alert elements using selenium in Java has been a bit challenging for me. Below is the code snippet I have been working on: import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import ...

Retrieve the Array Object's Name in a JSON File

I am looking for city names like Salem and Madurai from the given JSON data { "status": "success", "DisplayList": [ { "AVINASHI": [ "gmail@com", "<a href="/cdn-cgi/l/email-protection" class= ...

"Utilize jQuery to make a call to a webservice

I created a java webservice and I am attempting to access it through jquery ajax, but I am only receiving the HTML page generated when calling the WSDL. Here is the snippet of JSP code: checkLogin = function () { $.ajax({ ur ...

Tips for updating the RadGrid component with JavaScript

An issue arises with this function: function UpdateTable(){ window.location.href="Form_ElameMamoreBazdid.aspx"; } ...

Jasmine service mocking: provider not found

Having recently started with unit testing, I am currently working on a codebase that includes a js file as follows: app.service("appService", function($http) { this.getData = function(url) { return $http.get(url); } this.foo = function() { ...

Illuminate a corresponding regular expression within a text input

I currently have a functional code for testing regex, which highlights matching patterns. However, my challenge lies in highlighting the result within the same input as the test string. Below you will see the HTML and JavaScript snippets along with two ima ...

Issue with XML Creation in Jgrid

When using Jgrid, I typically inject data into the grid using Xml like most of us do. My current requirement is for a batch update to the database. When I click on "Save Change," I need it to generate the Xml of the current, updated grid data. So, how ca ...

Is it possible for PHP to delay its response to an ajax request for an extended period of time?

Creating a chat website where JavaScript communicates with PHP via AJAX, and the PHP waits for the database to update based on user input before responding back sounds like an intriguing project. By using a recall function in AJAX, users can communicate ...