Concentrating on individual text inputs is ineffective in this situation

Before we proceed, please take a moment to check out this fiddle link: http://jsfiddle.net/asif097/z6zsc

What I am aiming for is to have this jQuery code execute independently for each text input with the specified class. Currently, it is affecting both text input fields simultaneously.

Below is the jQuery code in question:

$(".first-name-input").after("<div class='first-name-input-value'>First Name</div>");

    $(".first-name-input").focus(function(){
        $(".first-name-input-value").hide();
    });

    $(".first-name-input").blur(function(){
        if($(this).val() == ""){
            $(".first-name-input-value").show();
        }

    });

    $(".first-name-input-value").click(function(){
        $(".first-name-input").focus();
    });

I attempted an alternative approach as well: http://jsfiddle.net/z6zsc/1

However, my attempts were unsuccessful. Any suggestions on how to resolve this issue?

Thank you.

Answer №1

It might be beneficial to consider utilizing the HTML5 placeholder attribute for your needs.

http://jsfiddle.net/NWLes/

<input type="text" class="first-name-input" placeholder="First Name" required="required"/>

Alternatively, you could correct your code by visiting: http://jsfiddle.net/vYtmC/

$(".first-name-input").after("<div class='first-name-input-value'>First Name</div>");
    $(".first-name-input").focus(function(){
        $(this).next().hide();
    });
    $(".first-name-input").blur(function(){
        if($(this).val() == ""){
            $(this).next().show();
        }

    });
    $(".first-name-input-value").click(function(){
         $(this).prev().focus();
    });

Answer №2

To ensure your event handlers target the specific object that triggered the event, you must refer to $(this).

If you need to interact with a neighboring element, you will have to locate that element in relation to the current this element.

In this case, since the .first-name-input-value object follows the first-name-input object, you can accomplish this using the following code:

$(".first-name-input").focus(function(){
    $(this).next().hide();
});

Just an FYI, if you are looking to implement HTML5 placeholder functionality, there are existing solutions available as pre-written shims. Instead of reinventing the wheel, consider using one of these ready-made options. A quick Google search should yield several choices for you to explore.

Answer №3

One way to enhance your input elements is by utilizing inline javascript, which can also be organized into a separate function...

Your modified html code would look something like this:

<input id="first_name" name="first_name" type="text" size="25" placeholder="First Name"
            onfocus="if (this.value == 'First') { this.value = ''; this.style.color = '#000000'; } " 
            onblur="if (this.value == '') { this.value = 'First'; this.style.color = '#909090'; } " 
            value="First"/>

This method will help achieve the desired outcome and can be applied individually to each input field...

For a demonstration, you can view an updated fiddle here- http://jsfiddle.net/z6zsc/8/

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

Any advice on applying jquery CSS to elements contained within a dynamically loaded div element?

element, I have encountered an issue with integrating a PHP file to process and display a table within a blank div element upon clicking a button. Despite applying styles from my style.css file, the jQuery mobile styles do not seem to be taking effect. I ...

Prevent rapid event triggers with a jQuery slider

I am currently working with an event function in JavaScript that involves a slider and a tooltip element. Here is the code snippet: //Hide the Tooltip initially tooltip.hide(); //Initialize the Slider slider.slider({ ...

Is it possible to append an attribute to input descendants of hidden elements using jQuery?

I'm facing a challenge with JQuery that I can't seem to overcome. As someone who is not very familiar with JQuery, I believe I may have gone about this the wrong way. Within my large form, there are certain conditions that dictate whether specif ...

Real-time Property Availability Widget

I need assistance with creating a website for a homeowner who wants to rent out their property. The client requires a feature that allows them to log in and easily mark individual days as available or unavailable for rental by choosing specific colors for ...

Tips for utilizing the router instance on a different HTML page within the Backbone JS framework

I'm new to Backbone JS and still learning its intricacies. In main.js, I have created a router class that is included in index.html. I've also created an object of that router class associated with the same HTML page. However, when I redirect t ...

Could my mental model be flawed? When a page is accessed using https, a relative css path will be invoked using the same protocol

When your page is accessed using the https protocol, any relative path to an external CSS file will also be called using the https protocol. Do you really need to encrypt/decrypt CSS content? :D However, if you use an absolute path to reference an external ...

Use JavaScript and PHP to retrieve a value from an array and dynamically populate select options based on that value

In my PHP code, I have two arrays structured like this: Array ( [0] => 11 [1] => 11 [2] => 11 [3] => 11 [4] => 11 [5] => 187 ) Array ( [0] => 118 [1] => 112 [2] => 85 [3] => 81 [4] ...

Hovering over a white background will darken the CSS styling

A stunning image on a dark background Displayed on Hover (right) An elegant picture with a white background Activated on hover (incorrectly) I would like it to have a darkened effect on the white background as well. CSS Styling .photo background: n ...

Downloading a PDF file on the server is not supported by React

import React from 'react'; import Navigation from "../components/Nagivation"; const Home = () => { return ( <div className="home"> <Navigation/> <div className="homeC ...

Maintaining responsiveness, CSS grid will automatically adjust the height of each element to be equal

I am facing an issue with my grid layout. Each element in the grid has an image and other divs below it. The problem arises when the screen size changes, causing the elements to scale automatically due to responsive width. I want all the images to have the ...

Tabulating with jQuery Arrays

I am facing an issue when trying to perform calculations with certain numbers. Here is the specific code snippet causing trouble: for (var key in week_total) { $("." + key).html(week_total[key]); } After running this code, I keep getting a value of N ...

The data type "100%" cannot be assigned to a number type in the kendo-grid-column

I need the columns in the grid to have a width of 100%. <kendo-grid-column field="id" title="id" [width]="'100%'"> </kendo-grid-column> However, when I hover over the code, I get this message: The value "100%" cannot be ...

The data retrieved through Ajax functions may vary between Chrome and Firefox browsers

There seems to be an issue with retrieving data from a POST request in different browsers. In Chrome, the data is returned successfully and appears as follows: {"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdacaeaea ...

Interactive multi-phase form with field populated by jQuery

Having an issue with a script that fills an input field when the value is less than 4. Unfortunately, when the value is less than 4, the script fills the field but doesn't select the value. This causes a problem when moving to the next step as there i ...

What are the steps to implementing partial page functionality with the $http service in Angular?

Could someone assist me with executing an operation once a partial page has been successfully loaded using the $http service in Angular? The operation involves checking a checkbox based on the scope value. I have included the source code below: Here i ...

I find the SetInterval loop to be quite perplexing

HTML <div id="backspace" ng-click="deleteString(''); decrementCursor();"> JS <script> $scope.deleteString = function() { if($scope.cursorPosVal > 0){ //$scope.name = $scope.name - letter; ...

Inheriting vertical height and alignment (inline-block)

I struggle to understand how these things work and I would greatly appreciate it if someone could provide an explanation. 1 http://d.pr/i/6TgE+ why http://d.pr/i/UAZn+ *it's actually 9. Here is the code snippet: <header> <div class=" ...

What is more effective: utilizing document fragments or string concatenation for adding HTML to the DOM?

My task involves adding a collection of cards to the DOM. html <div class="card"> <div class="card-title">Card 1</div> <div class="card-subtext">This is card 1</div> </div> js let ...

Resolved issue with background image display on Mac Chrome

I'm currently in the process of developing a website that incorporates fixed background images for smooth transitions between sections. The implementation is entirely CSS-based and has been effective in all browsers except for one: Chrome on Mac (Vers ...

Exploring the capabilities of jQuery's .post function within a custom template form on Wordpress

I am currently developing a customized contact form for a WordPress website and attempting to submit it via ajax with the help of jQuery. However, I am encountering a 404 error in the console when using the $.post function, even though I can access the URL ...