What is the best way to display and conceal an input label when focusing in and out?

This is a snippet of my HTML code:

<label for="first_name">First Name</label>
<input class="w3-input" type="text" name="first_name" id="first_name">

<label for="last_name">Last Name</label>
<input class="w3-input" type="text" name="last_name" id="last_name">

When clicking on an input, I want to hide the corresponding label in order to achieve certain results. I attempted to implement this using jQuery, but it doesn't seem to be working as expected.

$(document).ready(function(){

 $(".w3-input").click(function(){
    var item_select = this.id; //getting the ID of the clicked item

     $(item_select).focusin(function(){
        $(this).prev("label").hide(); //hiding the label of the clicked item 
    });
      $(item_select).focusout(function(){
        $(this).prev("label").show();
    });
 });

}); 

I'm confused about what's wrong with my code. Can anyone please help me solve this issue?

Thank you

Answer №1

You don't actually require the click.

$(document).ready(function(){
  $(".w3-input").focusin(function(){
    $("label[for='" + $(this).attr("id") + "']").hide();
  });
  $(".w3-input").focusout(function(){
    $("label[for='" + $(this).attr("id") + "']").show();
  });
}); 

Fiddle

Answer №2

The issue lies in the fact that the focusin handler is being registered within the click handler. This results in the focusin event being triggered before the click event, leading to a situation where there is no focusin handler available during the initial click. Additionally, this setup causes multiple handlers to be added with each subsequent click.

It is unnecessary to rely on the click event for this functionality.

$(function() {

  $(".w3-input").focus(function() {
    $(this).prev("label").hide(); // hide label of clicked item
  }).blur(function() {
    $(this).prev("label").show();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="first_name">First Name</label>
<input class="w3-input" type="text" name="first_name" id="first_name">

<label for="last_name">Last Name</label>
<input class="w3-input" type="text" name="last_name" id="last_name">

Answer №3

Try using the code $('#'+item_select)

$(document).ready(function(){

 $(".w3-input").click(function(){
    var item_select = this.id; //retrieve id of clicked item
        console.log(item_select)
     $('#'+item_select).focusin(function(e){//add # to target id
        $(this).prev("label").hide(); //hide label of selected item 
    });
      $('#'+item_select).focusout(function(){//add # to target id
        $(this).prev("label").show();
    });
 });

}); 

Check out the demo here

Your current solution may not function properly if you have not clicked on the input field before. Try removing the click event for it to work correctly.

View the updated DEMO 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

Incorporate a video within the royal slider feature

Next is my deluxe slider code. This slider displays only images but I am looking to incorporate video as well. I have searched online and tried different solutions, but haven't found one that works for me. Can someone please guide me on how to achieve ...

Having trouble getting the Bootstrap 4 Modal javascript trigger to function properly?

I am facing a challenge with displaying my modal after asking the user to authenticate. The modal content overrides server files, so I want the user to authenticate before viewing it. My idea is to have the user click on an editmodal button, which will th ...

Incorporating Ajax content in Struts 2 with the Struts2 Dojo Extension

I'm facing a minor issue with loading content through an Ajax call in Struts 2 (using the Struts2 Dojo Plugin). It's able to load all the HTML content from the page successfully, but it seems to have trouble loading any inline JavaScript function ...

Using Bootstrap v4 to create an Inline Select with Text

Currently seeking an inline dropdown styled with Bootstrap v4 that resembles the following: https://i.sstatic.net/ZTs8b.gif I have experimented with several options, and so far the closest one is as follows: <div class="dropdown"> <button cla ...

Creating a custom blockquote style for a WordPress Twenty Fifteen child theme

Currently, I am creating a new child theme for Twenty Fifteen completely from scratch. The one area I am struggling with is customizing the appearance of the blockquote using CSS. Here is an example of the custom CSS I have added to the blockquotes within ...

Bootstrap form: Functioning custom file button not displaying uploaded file name

My Bootstrap form features dual columns (built with Bootstrap 4.3) and includes a custom file upload button. While the button allows for file selection and successful uploads, it does not display the uploaded file's name post-upload (instead of showi ...

Is there a way to reference a background-image using "<img src>" syntax?

Why won't the background image display? It only displays as an img src. How can I call the background-image correctly? <body> <div id="page" style="background- image:url(https://storage.blob.core.windows.net/name/image.png)"> ...

Error: String cannot be used for function prepare()

Before posting this, please wait to ensure it's not a duplicate. I've conducted thorough research and attempted all solutions, but still unable to resolve the issue. I consistently receive the error message "Fatal error: Call to a member function ...

Unable to prevent default behavior when submitting a form

I have been experiencing an issue where my HTML form reloads the webpage upon submission, despite including the e.preventDefault() command in my submission function. $("#room-code-form").addEventListener("submit", function(e) { e.preventDefault(); }); ...

Position: fixed CSS child element ignoring parent's layout constraints

When a parent element is positioned (using position: relative or position: absolute) and contains a child element with position: absolute, the child element will be positioned absolutely inside the parent. A child element with position: sticky will behave ...

Object of Razor enclosed within an anchor tag

Exploring the realm of MVC 4 and Razor is new to me. Currently, I am attempting to create a Gallery with "CSS3 Lightbox". Everything seems fine, but I am encountering difficulties with Razor and links. The issue lies in my understanding of the pre and ne ...

Incorporate personalized design elements within the popup component of Material-UI's DataGrid Toolbar

I am in the process of customizing a Data Grid Toolbar component by making adjustments to the existing Grid Toolbar components sourced from Material-UI. For reference, you can view the official example of the Grid Toolbar components here. Upon clicking o ...

Loading Jquery autocomplete on page load

I have implemented the jquery autocomplete plugin and it is functioning correctly. However, I am looking to automatically trigger the select function if there is only one item in the dropdown list, so that fields are populated without any user interaction. ...

Using jQuery to reveal or conceal content based on a particular class

Being a beginner in jquery, I have a question that might seem silly but I've searched everywhere for an answer without success. So, here it goes: I'm trying to display different content based on the option selected in a dropdown form. According ...

Issue with starting tubular jquery video on Safari 7 (mac)

I'm currently utilizing the tubular plugin () to generate a subtle HTML video background. Everything is functioning smoothly in Chrome, however, when attempting to run it on Safari 7 for Mac, the video fails to start. After some investigation, I&apos ...

The functionality of the input text field being draggable and resizable is not functioning properly

I have created a plunk where I implemented jQuery resizable and draggable on an input field of type text. However, I am facing two issues. Firstly, the draggable functionality is not working as expected. Secondly, the resizable feature only seems to work w ...

Can you provide instructions on creating a marker like this in an unordered list?

Is there a way to create a bold line like this within a bulleted list easily? https://i.sstatic.net/pw8Zt.png I've tried using the border property, but it's not showing up correctly. Any quick and simple solutions for achieving this effect? Th ...

Arranging shapes for optimal placement on a web page

I recently created a vibrant red SVG shape that resembles this: https://i.sstatic.net/E3P3O.jpg My goal is to incorporate these shapes into a design that looks like the following: https://i.sstatic.net/8Yf8L.jpg I attempted to embed the SVG file in an ...

Steps to bring an image forward on a canvas to enable its onclick function

One of the challenges I'm facing involves an image of a pawn on a board. The image is set up with an onclick function that should trigger an alert when clicked. However, there is a canvas positioned above the image, which is interfering with the funct ...

By utilizing the <tr> element, one can enhance the border thickness by 1 pixel

Is it possible to ensure that row selection in a table is consistent in terms of border alignment on both sides? https://i.stack.imgur.com/qmZiQ.png If you have any suggestions or solutions, please share them. Thank you! table { margin: 10px; bord ...