JQuery keyup event - troubleshooting show/hide errors

There seems to be a problem with the jQuery keyup function. Currently, when data is entered into one field, errors in all other fields are hidden. However, the desired behavior is to show or hide only the error message for the specific field being interacted with.

$('#trexright input').keyup(function() {
  if ($(this).val().length != 0) {
    $('.field_error').hide();
  } else {
    $('.field_error').show();
  }     
});
#trexright p,
.form_field input {
  width: 100%;
}

#trexright span {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div id="trexright">
<p class="form-row">
  <label for="first_name" class="">First Name</label>
  <span class="woocommerce-input-wrapper">
    <input type="text" class="first_name_class" name="first_name" id="first_name_id" placeholder="First name" value="">
  </span>
  <span class="field_error">This field is required.</span>
</p>

<p class="form-row">
  <label for="last_name" class="">Last Name</label>
  <span class="woocommerce-input-wrapper">
    <input type="text" class="last_name_class" name="last_name" id="last_name_id" placeholder="Last name" value="">
  </span>
  <span class="field_error">This field is required.</span>
</p>

<p class="form-row">
  <label for="location" class="">Location</label>
  <span class="woocommerce-input-wrapper">
    <input type="text" class="location_class" name="location" id="location_id" placeholder="Location" value="">
  </span>
  <span class="field_error">This field is required.</span>
</p>
</div>

Answer №1

It seems like you are toggling the visibility of all .field-error elements.

To properly link the changed input ($(this)) with its corresponding field-error, you need to establish a connection between them.

Given the current HTML structure, you can utilize the next() method to target the field-error that follows the input.

UPDATE: With the modified HTML structure by OP.

Now that field-error is no longer a sibling of the input, using next won't work. Instead, you should select the parent element of the input (i.e., span) and then use next to pinpoint the field-error.

I have also tidied up the code for better readability.

TIP: I recommend delving into jQuery methods to enhance your understanding of traversing HTML structures for selecting specific elements. Furthermore, consider dabbling in vanilla JavaScript as an alternative to relying solely on jQuery, particularly in extensive projects.

$('#trexright input').keyup(function() {
  const inputError = $(this).parent('span').next('.field_error');
  $(this).val().length > 0 ? $(inputError).hide() : $(inputError).show()
 
});
#trexright{
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="trexright">
<p class="form-row">
  <label for="first_name" class="">First Name</label>
  <span class="woocommerce-input-wrapper">
    <input type="text" class="first_name_class" name="first_name" id="first_name_id" placeholder="First name" value="">
  </span>
  <span class="field_error">This field is required.</span>
</p>

<p class="form-row">
  <label for="last_name" class="">Last Name</label>
  <span class="woocommerce-input-wrapper">
    <input type="text" class="last_name_class" name="last_name" id="last_name_id" placeholder="Last name" value="">
  </span>
  <span class="field_error">This field is required.</span>
</p>

<p class="form-row">
  <label for="location" class="">Location</label>
  <span class="woocommerce-input-wrapper">
    <input type="text" class="location_class" name="location" id="location_id" placeholder="Location" value="">
  </span>
  <span class="field_error">This field is required.</span>
</p>
</div>

Answer №2

Give this a try and it should work smoothly.

$('#trexright input').keyup(function() {

  if ($(this).val().length != 0) {
    $('input:focus').next('.field_error').hide();
  } else {
    $('input:focus').next('.field_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

Vanish and reappear: Javascript block that disappears when clicked and shows up somewhere else

My goal is to make three squares randomly disappear when clicked on the page. However, I am facing an issue where some of them, usually the 2nd or 3rd one, reappear elsewhere on the page after being clicked. I have created a jsfiddle to demonstrate this: ...

Arrangement of divs on a stretched background

Seeking assistance to code a layout using div layers that resembles the design in this sample: The concept involves dividing the background into 4 distinct sections with content placed centrally. The upper part will feature a main banner image over pink a ...

Retrieve the most recent update timestamp of a file stored on a distant server

Is there a way to use curl to retrieve the last modified date of a file on a remote server? I'm looking for some guidance on how to accomplish this. ...

Ways to customize the appearance of Bootstrap 4 tooltips

I'm having trouble customizing my Bootstrap 4 tooltip. I want to adjust the background color, height, width, and border, but I can't figure out how to style it to my liking. Here is the HTML code I am using: <i class="fa fa-question-circle" ...

Jquery-ajax fails to accomplish its task

I am just starting to learn about ajax and recently created a simple page on my local server to practice sending and receiving data from/to a JSON file in the same directory. Although the GET method is working perfectly fine, I am having trouble understan ...

Experiencing varying top offsets on initial click followed by consistent offsets on subsequent clicks

The first image shows jquery(document).height() and the second image shows offset().top. I am attempting to scroll to an element with a fixed header, but on the first click I get a different value for offset().top than on the second click. It seems that th ...

Issues with Carousel Plugin Functionality

**Hey everyone, I could really use some help. As a beginner coder, please forgive any errors in my code. I am currently working on a webpage where I need to incorporate a carousel plugin within a panel body to display the latest photos. The code provided ...

When attempting to POST data in Laravel, a status of 419 (unknown) is returned and the data cannot be posted to the target URL

I am attempting to create a DOM event that triggers when a user clicks on a table row's header (th) cell, deleting the corresponding row from the database that populates the table. Previously, my code worked as expected without any framework. I simpl ...

Is it possible to use CSS position relative without specifying a relative width?

I am looking for a way to have an element with relative positioning without its child element (using position:absolute) inheriting relative width from the parent. Take for example this scenario: http://jsfiddle.net/t2yJP/. How can I achieve the second bod ...

in vuejs, a legendary row is added to the table every 25 or 50 records

VueJS v-for is functioning properly: <tr v-for="request in requests"> <td>{{request.name}}</td> <td> .. etc .. </td> </tr> Now, I want to insert a legend row after every 25 or 50 records. Here's what I tri ...

Transparent static navbar displayed above header image

Scenario I managed to develop a transparent navbar that is superimposed on top of a header image with an SVG curve attached to it. To create the transparent navbar, I modified some classes associated with it by removing bg-light. By adding the class fix ...

Creating an svg ring using css: a step-by-step guide

Is there a way to create a ring in an SVG using CSS? I have the desired shape using a polygon, but I am looking for a method to achieve the same effect with a ring: clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%, 0 0, 6vh 0, 6vh 61vh, 44vh 61vh, 4 ...

Solution for repairing the display location button on Android within a React Native Map

I am facing an issue with the Location Button in my React Native Maps app. When the app is opened for the first time and the map is rendered, the button disappears. However, if I close the app but leave it running in the background, upon reopening the app, ...

Error encountered in JSP page while using JavascriptMVC in Tomcat 7

I am currently developing a web application using SpringMVC for the server side and JavascriptMVC for the client side. I have successfully integrated JavascriptMVC with HTML pages, but now I am facing an issue when trying to incorporate it with my JSP page ...

Is it possible to have one div layer on top of another?

On my website, I have a line of text that is revealed when a dropdown arrow is clicked. However, there are certain pages where the divs extend beyond this single line of hidden text. For example: https://i.sstatic.net/2a6YB.png I need the green div (nor ...

The font displayed in Photoshop Mock Up may not be identical to the font used in HTML

(HTML Newbie) I created a design using Photoshop for my website, but the text appears differently when viewed in Firefox. I used Arial font, 18pt size, and regular weight in the mock-up, and implemented it into HTML code, yet it displays differently. Is ...

When using my webrtc technology, I configure my sdp to establish a recvonly direction

While attempting to make a video call using WebRTC, I encountered bugs during testing. My goal is to integrate this project into a webview for my Android app. I conducted testing using phone-pc and phone-phone scenarios. Scenario A: When the PC initialize ...

What could be causing the error in this code's output?

Being new to PHP programming, I encountered an issue while trying inputting an HTML tag into a PHP file. This snippet generated an error: <?php $a = "Begin"; $b = 12; echo $b . " " . $a . " " . "This is a PHP file <br/>"; echo strlen($a); echo s ...

Navigate through each element with a specific class name in a block of HTML code using

Currently, I am dealing with an HTML string that is being retrieved through AJAX. Let's assume it looks like this: var htmlString = '<div class="post"></div><div class="post"></div>'; I want to find a way to iterat ...

The TipTap Editor does not properly register spaces

In our project, we are utilizing the TipTap rich text editor. However, we are encountering an issue where spaces are not being recognized correctly - a space is only created after every 2 clicks. Our framework of choice is Vue.JS. import { Editor, EditorC ...