Ensure that the default value in the text box remains unchanged until new text is input by utilizing jQuery

Can you please review my code snippet on http://jsfiddle.net/7995m/? The issue I'm facing is that the default text in the text box disappears as soon as it's clicked. What I want is for the default text to remain until the user starts typing. Here's the code I've written:

$(".defaultText").focus(function(srcc)
{
    if ($(this).val() == $(this)[0].title)
    {
        $(this).removeClass("defaultTextActive");
        $(this).val("");
    }
});

$(".defaultText").blur(function()
{
    if ($(this).val() == "")
    {
        $(this).addClass("defaultTextActive");
        $(this).val($(this)[0].title);
    }
});

$(".defaultText").blur();        

Answer №1

Start using the HTML5 placeholder attribute by checking out this resource: http://davidwalsh.name/html5-placeholder

This attribute is commonly utilized in web applications.

If your targeted browser doesn't support placeholders, consider creating a polyfill with modernizr to ensure compatibility with the html5 attribute. Here's an example of a polyfill using jquery: https://github.com/mathiasbynens/jquery-placeholder

You can explore additional polyfills for placeholders and other html5 attributes here: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

Refer to modernizr through this link:

Once you implement the polyfill, modernizr will check if the browser supports the placeholder attribute. If not, the polyfill will mimic its functionality. This approach keeps your HTML clean without custom solutions that may cause compatibility issues with future browsers.

Using a polyfill like this is the optimal choice. While custom solutions work initially, relying on a polyfill prevents potential issues in the long run. It ensures your application remains functional even as new browsers emerge, maintaining the same capabilities across different browser versions. Additionally, it enhances the readability of your HTML code.

Answer №2

If you want to minimize your code size, consider utilizing the placeholder attribute.

For example:

<input type="text" name="last_name" placeholder="Enter your last name...">

See Demo on Fiddle

Answer №3

check out this working fiddle

To improve the functionality, consider replacing the focus with keydown. While a placeholder is a good option, keep in mind that IE7,8,9 do not support it. Instead of using JavaScript polyfills, you can stick with the current code provided.

$(".defaultText").keydown(function(srcc) {
    if ($(this).val() == $(this)[0].title) {
        $(this).removeClass("defaultTextActive");
        $(this).val("");
    }
});

$(".defaultText").blur(function() {
    if ($(this).val() == "") {
        $(this).addClass("defaultTextActive");
        $(this).val($(this)[0].title);
    }
});

$(".defaultText").blur();

Answer №4

One option is to utilize the placeholder attribute.

Answer №5

For achieving this specific behavior, consider using the following script within your focus event:

$(".defaultText").keydown(function(event)
{
    $(this).removeClass("defaultTextActive");
    $(this).val("");
});

However, it is recommended to use the placeholder tag as it is the standard way to achieve similar functionality.

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

How can I ensure that each callback is passed a distinct UUID?

I am utilizing a package called multer-s3-transform to modify the incoming image before uploading it to my bucket. Below is the code snippet of how I am implementing this: const singleImageUploadJpg = multer({ storage: multerS3({ s3: s3, bucket: ...

Employing jQuery for element rotation via swipe/drag movements

I am looking to create a dynamic experience where a circle rotates in sync with the user's swipe or drag gestures on the screen. Currently, I am developing an app using Phonegap and considering integrating hammer.js as it comes highly recommended by m ...

Are promises perpetually in a state of limbo? (incorrect format

As a newcomer to node.js, express, and ES6, I am learning the ropes and trying to write cleaner, more efficient code using ES6 functions and promises. One issue I'm facing is with inherited functions and values, particularly next(). Here's the co ...

Obtaining JSON data using Jquery results in the output of "undefined"

I am struggling to extract the correct values from a JSON document in order to display schedules in list view. Currently, when accessing the JSON document, I keep receiving "undefined" as the result. Below is an example of the JSON document: { "Ferries": ...

Capturing HTML content with jQuery

There is a hyperlink to a page (with HTML code, on the same domain) that contains an image with matching title and alt attributes. The script needs to follow the hyperlink, retrieve the source attribute of the image with the matching title and alt, and as ...

Loading data into a text field using JQuery, AJAX, and PHP when a checkbox is clicked

Is there a way to automatically populate text fields with data when a checkbox is clicked, and then disable the field? And if the checkbox is unchecked, remove the data and enable the text field for manual input. I have attempted to implement this using ...

What is the preferred method for verifying AJAX success when the server's response is either true or false?

My server response can be either true or false. I've been attempting to determine how to check for success based on the returned value being true or false using the script below: $('form[data-async]').on('submit', function(event) ...

Learn how to retrieve the TextBox value from a button click within a Nested Gridview

I am trying to extract the value of a textbox inside a Nested Gridview using jQuery in ASP.NET. When a Button within the Nested Gridview is clicked, I want to display the textbox value in an alert box. Here is an example setup: <asp:GridView ID="Grid ...

How to use jQuery to remove an empty <ul> tag

Here is the code snippet I am working with: ` <ul id="jsddm"> <li><a href="Default.aspx"> Menu</a> <ul style="visibility: hidden;" ...

Assigning a default value to a date picker within a dynamically created form after making an AJAX call

Hey there, I've been delving into AngularJS lately. Currently, I'm working on a POST AJAX call that retrieves data which I use to create a form. Within this form, there are two input fields that serve as date pickers. I've been struggling t ...

Mapping memory for FirefoxOS is like equivalent strides

Is there a way to create a memory mapped file in FirefoxOS, Tizen or other pure-JS mobile solutions? In the scenario of a mobile browser where you have large amounts of data that can't fit in RAM or you prefer not to load it all at once to conserve R ...

Encountered an error while trying to create a new NestJS project using yarn: Command execution failure - yarn install --

Having trouble installing a new NestJs project using yarn. Operating system : Microsoft Windows [version 10.0.19044.3086] Node version : 18.17.1 npm version : 9.6.7 yarn version : 1.22.19 Nest cli version : 10.1.16 I attempted to install by running : npm ...

What is the reason for the successful insertion into the database without including "http://" but encountering errors when including "http

How can I insert a site title, site address (URL), site description, and site category into my database using jQuery/JSON on the front-end? When I enter "http://" in the site address input field, the data is not inserted into the database. Here is the cod ...

Retrieve JSON information from a URL via AJAX if applicable

Is there a way to retrieve the JSON data from the following URL and incorporate it into my webpage in some capacity? (Disclaimer: I do not own this website, I am simply utilizing the data for a basic free app.) Although entering the URL directly into the ...

What's the best way to toggle the visibility of an input-group in Bootstrap?

Is there a way to properly hide and show a Bootstrap 5 input-group? You can see an example here: https://jsfiddle.net/o08r3p9u I'm facing an issue where once the input group is hidden, it doesn't show correctly when displayed again. How can I e ...

Connect main data to sub-component

Example Vue Structure: <Root> <App> <component> Main function in main.js: function() { axios.get('/app-api/call').then(function (resp, error) { _this.response = resp.data; }) ...

Tips for saving an image that has been dragged onto the browser locally

I recently started working with Angular and decided to use the angular-file-upload project from GitHub here. I'm currently in the process of setting up the backend for my application, but I'd like to be able to display dropped files locally in th ...

What steps should I take to fix the error "Unused left side of comma operator with no side effects.ts(2695)" in my React project?

import React from "react"; import { useRecoilState } from "recoil"; import { Industry, industryState } from "../atoms/industriesAtoms"; const manageIndustryData = () => { const [industryStateValue, setIndustryStateValue] ...

A step-by-step guide on making a web API request to propublica.org using an Angular service

Currently, I am attempting to extract data from propublica.org's congress api using an Angular 8 service. Despite being new to making Http calls to an external web api, I am facing challenges in comprehending the documentation available at this link: ...

Efficiently repositioning Kendo Mobile Buttongroup to a new row as needed

In my current project, there is a specific requirement to display three button groups in a row. If there are more than three buttons, they should move to the next row dynamically as the data will be fetched from the server. For reference, below is a sampl ...