Difficulty in displaying errors for specific spans

Upon receiving the json data from another page, it typically resembles:

data :

{"BusNo":["The bus no field is required."],"CompID":["The comp id field is required."],"TotalSeats":["The total seats field is required."]} 

Below is my Script :

$(document).ready(function() {
    $("#driver").click(function(event) {
        var BusNo = $("#BusNo").val();
        var CompID = $("#CompID").val();
        var TotalSeats = $("#TotalSeats").val();
        var _token = $("#_token").val();
        $.post("managebus_register", {
                _token: _token,
                BusNo: BusNo,
                CompID: CompID,
                TotalSeats: TotalSeats
            },
            function(data) {
                if (data != '') {
                    var obj = JSON.parse(data);
                    $.each(obj, function(entry) {
                        var targetSelector = '';
                        if (entry == "BusNo") {
                            targetSelector = "#BusNo";
                            console.log('error in bus field');
                        }
                        if (entry == "CompID") {
                            targetSelector = "#CompID";
                            console.log('error in comp id');
                        }
                        if (entry == "TotalSeats") {
                            targetSelector = "#TotalSeats";
                            console.log('error in total seats');
                        }
                        if (targetSelector)
                            $(targetSelector).next("span.error").html(obj[entry]);
                        else {
                            $(targetSelector).next("span.error").text(' ');
                        }
                    });
                } else {
                    console.log('pass');
                }
            });
    });
});

The script looks for errors within the condition if(data != '') and assigns a specific selector such as targetSelector = "#BusNo";

An issue arises where error messages persist even after input fields are corrected.

In this part of the script:

if (targetSelector)
    $(targetSelector).next("span.error").html(obj[entry]);
else {
    $(targetSelector).next("span.error").text(' ');
}

The statement

$(targetSelector).next("span.error").text(' ');
in the else section does not function as intended.

I have discovered that

$("span.error").empty();

would resolve this issue.

However, I aim to highlight the input text box with errors and display the error message only on hovering over the respective field. Here's an example markup:

<input type="text" id="BusNo" name="BusNo"/><span class="error"></span>

<input type="text" id="CompID" name="CompID"/><span class="error"></span>

Answer №1

Modifications in the code:

if (targetSelector)
   $(targetSelector).next("span.error").html(obj[entry][0]);
else {
   $(targetSelector).next("span.error").text(' ');
}

If displaying error on hover is desired:

$("input").hover(function(){
    var id = $(this).attr("id");
    $("input").next("span.error").hide();
    $("#"+id).next("span.error").show();
})

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

Retrieve parameters from functions and convert them into coherent statements

As I delved into the world of THREE.js, I experimented with various geometries. However, manually writing out each geometry became tedious due to the vast array of options available. For example, creating a simple cube required these lines of code: var m ...

Tips for handling an AJAX form submission with various submit buttons and navigating through Laravel routes

I am having trouble getting the form below to submit to the database. The issue arises when trying to use AJAX to submit the forms. The problem seems to occur at this point: $(i).submit(function(event) { Can someone help me figure out what I am doing wr ...

Transform large integer values into an array consisting of individual digits

I'm attempting to store the individual digits of a large integer in an array by converting it to a string first and then using the 'split()' method. However, it seems that in JavaScript, this method only works for integers up to 15 digits. F ...

What is the process for sending an HTTP post request with a React/Typescript frontend and a C#/.Net backend?

In the frontend code, there is a user login form that accepts the strings email and password. Using MobX State Management in the userstore, there is an action triggered when the user clicks the login button to submit the strings via HTTP post. @action logi ...

Unable to implement select2 in a modal with a dynamic table

//snippet of code from the controller for every medical package in $medical_packages { concatenate html table row with details of the package } //the classes used are search select, they are dynamically generated in a table inside the modal //sni ...

Deploying scripts after CloudFormation deployment

After each deployment on AWS, I have a specific npm script called db:migrate that I need to run. This script is responsible for executing the migrate.js file, which handles all database migrations. Currently, my deployments are managed using AWS CloudForm ...

Is it possible to load babel-polyfill using <script async> tag?

I have created a modal dialog on my webpage that appears when certain interactions occur. Utilizing React, I used webpack to generate a compact bundle that can be added to my page using a script tag. Since it incorporates Generators and needs to support ...

Is the parameter for the success function in Ajax empty?

When I receive an empty success function parameter 'lewa', but it works when I change it to 'order' (order.vnaam). Can anyone help me identify the issue? $(document).ready(function() { $.ajax({ type: 'POST', ...

Working with nested JSONArrays in Android

Looking at the json data snippet below: "categories": [ [ "Belgian Restaurant", "belgian" ], [ "Brasserie", "brasseries" ] ], I am trying to extract information from the second JSONArray (in thi ...

Vue.js - Testing components with intricate child components

Imagine we have a simple Bootstrap powered HTML form within a custom Vue component named MyForm.vue <template> <form> <div class="form-group"> <label for="email">Email address</label> <input type="email" ...

Creating sleek HTML5 applications in the Windows 8 Metro style

Is it possible to develop a metro style Windows 8 HTML5 application without having Windows 8 OS installed? I know how to work on VS2012, but since it's a web application, I don't see the need for Windows 8 OS. Please let me know if it's nece ...

Dynamically load an external JavaScript file based on the presence or absence of specific elements on the webpage

Hi there, I have a question for you all. Situation: We are using a javascript tool to conduct A/B testing on our landing page designs. I want version A (control) to be linked to one external javascript file, while version B (variation) is linked to a diff ...

Sending an AJAX request to submit a form and receiving a response

I am in the process of developing a Rails application and I am seeking a way to submit a form using Ajax. This functionality is crucial as I want the form submission to occur without causing a full page reload. Initially, I tried using form_remote_tag but ...

How to achieve a reverse slideToggle effect with jQuery when refreshing the page

After creating a custom menu on Wordpress using jQuery slideToggle to toggle dropdown on hover, everything seemed to be working perfectly. However, I noticed that when I refreshed the page while moving my cursor between two menu items with dropdown menus, ...

Decoding JSON with dynamic keys in Elm

Looking to extract information from a Json file structured like this: { 'result': [ {'id': 1, 'model': 'online', 'app_label': 'some_app_users'}, {'id': 2, 'model': &a ...

Retrieve a specific line of code from a snippet of JavaScript

I am looking to extract a specific line of code from a script that I am receiving via ajax... The line in question is new Date(2010, 10 - 1, 31, 23, 59, 59) found within the following snippet: jQuery(function () { jQuery('#dealCountdown').count ...

Mapping the correct syntax to apply font styles from an object map to the map() function

React, JS, and Material UI Hey there, I have a question about my syntax within the style property of my map function. Am I missing something? Fonts.jsx export const fonts = [ { fontName: 'Abril', key: 'abril', fontFamily ...

What is the best method for inserting a BigInt value in Node.js using MongoDB Driver?

Attempting to insert a BigInt value into my MongoDB Database using the Node.js Mongo Driver. I have attempted to use BigInt, but it fails to successfully insert the number (expiry) into the document. let expire = BigInt(parseInt((Date.now() / 1000) + 216 ...

ID not processing JSON data into HTML markup

I'm currently using PHPstorm IDE and encountered an issue while trying to display JSON content in HTML format. The problem is that only the <ul></ul> tags are being rendered, without the <li> elements being converted into HTML by the ...