Having difficulty with utilizing the validate() function in jQuery

My HTML code looks like this:

<form class="form-filter" id="form-filter-excel" role="form">
            <div class="row">
                <div class="col-md-4 col-sm-5">
                    <label>Date range</label>
                    <div class="input-group input-daterange datepicker">
                        <input id="fRange" name="fRange" class="form-control input-sm" type="text">
                        <span class="input-group-addon bg-primary">to</span>
                        <input id="sRange" name="sRange" class="form-control input-sm" type="text">
                    </div>
                </div>
                <div class="col-md-2 col-sm-1">
                    <label>
                        &nbsp;
                    </label>
                    <a class="btn btn-wide btn-primary form-control" href="#" id="btnexport" ><i class="fa fa-file-excel-o"></i> Export To Excel</a>
                </div>
            </div>
        </form>

This is where my screen shot ends: https://i.sstatic.net/PebVw.png

My question is about using validate() in jQuery. I am trying to use class= "input-daterange" as a field, with the inputs fRange and sRange being required. However, when I use fRange and sRange as fields, the error message gets messy. Any ideas on how to achieve this?

UPDATE: Apologies for not clarifying my question earlier. I am using jQuery validate as shown below:

$('#form-filter-excel').validate({
            highlight: function(element) {
                $(element).closest('.form-group').prop('required', true);
            },
            unhighlight: function(element) {
                $(element).closest('.form-group').prop('required', false);
            },
            errorElement: 'span',
            errorClass: 'help-block',
            errorPlacement: function(error, element) {
                if(element.parent('.input-group').length) {
                    error.insertAfter(element.parent());
                } else {
                    error.insertAfter(element);
                }
            },
            rules: {
                fRange: {
                    required: true,
                    date: true
                },
                sRange: {
                    required: true,
                    date: true
                }
            },
             messages: {
                fRange: "Please insert these input",
                sRange: "Please insert these input"
            },
        });

        $('#btnexport').click(function() {
            $('#form-filter-excel').valid();

            if($('#form-filter-excel').valid()==true)
            {
                var Fod = $('#fRange').val();
                var Tod = $('#sRange').val();

                window.open(host+"ajax/excelpoinfo?Fod=" + Fod +"&Tod=" + Fod, '_blank'); 
            } 
        });

The issue I'm facing is that the error message does not show under my input as intended, but appears differently on my screen. Here is the image of the error: https://i.sstatic.net/T82vx.png

I would like the error message to display under each input.

UPDATE: I have decided to use sweet alert instead. Thank you for the help. And to Mayank Pandeyz, please make sure to understand my question clearly before providing assistance. Changing the error placement did not resolve the issue.

Answer №1

To properly label both textboxes, be sure to add the name attribute with their corresponding values:

<form id="frmDetails" name="frmDetails">
  <input type="textbox" name="fRange">
  <input type="textbox" name="sRange">
</form>

For validation purposes, include the following code:

$('#frmDetails').validate({
    rules:
    {
        fRange: {
            required: true
        },
        sRange: {
            required: true
        }
    },
    messages:
    {
        fRange: {
            required: "Please select fRange"
        },
        sRange: {
            required: "Please select sRange"
        }
    }
});

Take a look at a working example here.

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

Deactivation within the directive does not entail a reset

Check out this Stackblitz In my Angular application, I implemented a Directive that disables a button after it's clicked to prevent double-clicking until a certain time has passed. <button appThrottleClick (throttleClick)="click()"> BUTTON & ...

What is the best way to send a prop for inline styling in a React component that contains an array of data?

My ShowData component is responsible for rendering in both my App.js and index.js files. import React from "react"; import SwatchData from "./SwatchData"; import { DataTestContainer } from "./DataTestContainer"; function ShowData(props) { const DataCom ...

Creating a serialized version of a string to be transmitted

Here is the code snippet I am working with: var serializeValues =$(this).find("input[type='hidden']).not('.table-element').serialize(); The Value: martial_status=%D0%B6%D0%B5%D0%BD%D0%B0%D1%82+(%D0%B7%D0%B0%D0%BC%D1%83%D0%B6%D0%B5%D0 ...

After submitting a post, the click event of a button in IE 10 using jQuery is not

The uploadButton feature allows users to upload an image and store it locally. I utilize fileinput to select the image, and when uploadbutton is clicked, the image data is sent back to the server. While this functionality works smoothly in Chrome, I encou ...

Pattern that determines the validity of a password

My current password validation pattern does not allow white space and requires at least 6 characters: /[^\s]+.{6,}/; I specifically need 6 characters that are anything except a space. However, this pattern is not functioning as expected. const ...

Is it possible to incorporate a fadein animation into a function?

Developing the entire HTML structure using JavaScript is one of my skills. Here is a snippet as an example: function generateHeader () { $('body').append( $('<header>') .attr('id', "main-header") ...

data.map` does not work as a function

I've encountered a persistent error that has me stumped. Here's the code snippet: JSON {"inventory": [ { "item_id" : "123", "item_data" : { "image_id" : "1234", "description" : "foo", "lin ...

External JavaScript file not executing defined function

My homepage includes a register form that should open when the register button is clicked. However, I am encountering an issue where the function responsible for opening the form from another JavaScript file is not being triggered. Here is the HTML code: ...

implementing a webpage enhancement that enables loading content asynchronously

I find myself puzzled. Lately, I've delved into learning Spring MVC through the development of a web application designed to display live sports scores in real-time. The core functionalities are already in place, but I'm unsure about how to creat ...

Ways to implement a conditional statement to display a div using JavaScript

Looking for a way to utilize Javascript conditions to toggle the visibility of a div in an HTML5 document? Check out this code snippet below: #demo { width: 500px; height: 500px; background-color: lightblue; display: none; } To set the f ...

Is it necessary to make a distinct route for SocketIO implementation?

I am new to Socket.IO and I recently completed the chat tutorial in the documentation along with some additional tasks to gain a better understanding of how it works. Currently, I am attempting to establish a connection between a NodeJS server and a React ...

Determining the Clicked Button in React When Multiple Buttons are Present

Within my functional component, I have a table with rows that each contain an edit button. However, when I click on one edit button, changes are applied to all of them simultaneously. How can I identify which specific button was clicked and only apply chan ...

Unlocking the Power of Angular: Transforming Input into Results

I'm currently exploring how to utilize an input field and fetch a response using Angular directly within the script. As a beginner, I came across this script on codepen. At the end of the code, I've attempted to make a call but haven't compl ...

Display modal after drop-down selection, triggered by API response

Currently, I am working on integrating an API to enable users to make payments through a modal. Users should be able to enter an amount and select a payment frequency. I have successfully extracted various payment frequencies from the API response and pop ...

Utilize JavaScript to implement CSS using an "if" statement

I am currently working on implementing iOS web app properties into my website. My goal is to create a <div> at the top of the page and apply specific CSS styles when a certain condition is met in a JavaScript script. Unfortunately, I am facing issue ...

Map the Ajax post data to the model being sent to the controller

I've been struggling to update a document with an Ajax call and bind the data from the call to the controller's model. What am I missing here? Changing the controller definition to expect a string helped avoid a NullReferenceException, but the p ...

How can you pause a YouTube video using jQuery?

My custom jQuery slider consists of three panels that slide smoothly by adjusting their left CSS values. Everything works perfectly, except for one issue - I have a YouTube video embedded in one of the slides, and it continues playing even when the slide i ...

Converting to lower case with Jexl and making replacements in the text

Currently, my code uses the jexl.eval function to evaluate a value like so: jexl.eval("dataset[0].data['Entity Name'].toLowerCase().replace(/ /g, '_')", data); The value of dataset[0].data['Entity Name'] is always a ...

Cascading Option Menus

I'm currently facing a challenge with three listboxes on a page. The first listbox can be filled with one of five different options. The second listbox's content depends on the selection made in the first listbox, and the third listbox is populat ...

What is the best way to eliminate items from an array in a side-scrolling video game?

In my gaming project, I am creating a unique experience where the player needs to collect all the words from a given array. Currently, I am utilizing the shift() method to eliminate elements, as demonstrated in the code snippet below: if ( bX + bird.width ...