Tips for displaying text in the input field that disappears when focused

Take a look at the jsfiddle link provided below:

http://jsfiddle.net/H49EC/1/

The example shows two search boxes with a button underneath. How can I make it so that text is initially present in each box but disappears when clicked on?

If a box is clicked on and nothing is entered, how can I make the text reappear?

Thank you for your help! I've been searching around but I'm unsure of what this feature is called or what language needs to be used.

Thanks again!

James

Answer №1

Make sure to utilize the placeholder attribute for your input fields.

<input type='text' placeholder='something' />

Answer №2

When working with HTML5, you have the option to utilize the placeholder="" attribute:

placeholder="Enter your text here"

http://jsfiddle.net/H49EC/2/


For situations where HTML5 is not being used, jQuery can be employed to modify the value (especially for older browsers and IE):

$('input').focus(function(){        
            // Clear the field's initial value on focus if it hasn't been changed
            if ( (this.value) == this.defaultValue ) this.value = '';    
        }).blur(function(){        
            // Restore the initial value if the field is still empty on blur
            if ( (this.value) == '' )   this.value = this.defaultValue;    
        })    

http://jsfiddle.net/H49EC/7/

Answer №3

In cases where older browsers need to be supported and the HTML5 placeholder attribute cannot be used, JavaScript can be utilized instead. The following code snippet serves as a starting point:

var inputField = document.getElementById("input1");
inputField.onfocus = function() {
    if(this.value === "Default") {
        this.value = "";  
    }
};
inputField.onblur = function() {
    if(this.value === "") {
        this.value = "Default"; 
    }  
};

For a demonstration of how it functions, refer to this revised fiddle. It is important to note that an id has been added to the input element for accessibility through getElementById. To extend this functionality to multiple inputs, consider creating a more general solution rather than targeting just one element.

Answer №4

Once, I successfully implemented a solution on a webpage using the infieldlabel tool from fuelyourcoding.com. It was effective in achieving the desired result, but it should be noted that this tool relies on jQuery as a plugin.

Answer №5

Are you referring to a placeholder?

Answer №6

This website provides assistance with implementing the placeholder attribute.

Currently, full cross-browser compatibility is not guaranteed, with IE posing the main challenge.

Visit this link for more information

Some developers are using divs to create workarounds for IE compatibility issues, where clicking on them hides the placeholders. A quick search on Google for "placeholder" will yield various solutions. :)

I hope this information proves helpful!

Answer №7

Solution is right at your fingertips.

<input type="text" name="searchText" placeholder="Type your search here!" />

Visit W3Schools to learn more about the placeholder attribute.

Take a look at this jsFiddle example for a quick demonstration.

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

Retrieving form data from within the resource error callback scope

For my client-side validation on submit, I am calling a resource if the form is valid. On success, everything works fine. However, when encountering an error handler, I also perform server-side validation on my data transfer object bean which contains Hibe ...

Having trouble accessing the property 'prototype' of null in Bing Maps when using Angular4

I'm currently working on creating a Bing component in Angular 4, but I'm facing issues with rendering the map. Below is my index.html file: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title> ...

Slider reset on postback, prevents slider from resetting on an ASP.NET website

I am facing an issue with a slider on my page. On page load, I have set a default value to the slider (25, 75). However, every time there is a postback inside the update panel after changing the slider value, it gets reset back to 25, 75. How can I prevent ...

What are the steps for creating a new npm package based on an existing one?

I'm a newcomer to the node ecosystem and the npm package system. In my redux/react web app, I currently make use of the photoswipe package alongside react-photoswipe. Recently, I decided to extend the functionality of the photoswipe package by making ...

Unnecessary list elements generated by dazzling navbarPage

While developing an app with shiny using navbarPage, I noticed that there are some unwanted li tags in the HTML that are not defined in my code. Could this be a known bug? How can I go about fixing it? <nav class="navbar navbar-default navbar-stati ...

Personalize your material-ui popover

Seeking assistance in customizing the shape of a material-ui popover similar to the one depicted in the image. https://i.sstatic.net/l5uNL.png I have created a working demo of the popover using React and provided a link for editing purposes. Any help? =& ...

Having trouble debugging JavaScript as a beginner? Unable to pull the cookie value and use it as a variable? Let's

Hello everyone, I'm new to coding and have been working on a project. However, I am facing some errors and need help debugging. I have a cookie named "country" with a value of "AZ" that I want to retrieve using JavaScript and use it in my Google Maps ...

Retrieving all rows from a table using Laravel API and Vue.js

<template> <div class="container"> <div class="row mt-5 mb-3"> <div class="col-md-10"> <h3>Gallery</h3> </div> <div class="col-md-2"> <button class="btn btn-success" ...

Error: Running the command 'yarn eg:'live-server'' is not a valid internal or external command

Currently, I am utilizing yarn v1.6.0 to manage dependencies. I have globally installed live-server by running the following command: yarn global-add live-server However, upon executing it as live server, I encounter the following error: 'live-ser ...

In order to work with the optionSelectionChanges property of the MdSelect directive in Angular Material2, it

Within my application, there is a Material2 select dropdown widget containing several options. app.component.html <md-select placeholder="Choose an option" [(ngModel)]="myOption" (optionSelectionChanges)="setOptionValue(myOption)"> &l ...

Adjusting the image width and height dynamically based on the parent container dimensions using CSS and HTML

I'm trying to utilize CSS to fill my window with an image while maintaining quality. Is there a way to maximize the width/height of the image until all the white space is filled without compromising its quality? <div class='rel-img-cont' ...

Enhance your dynamic php page with the use of a light box feature

Hey, I have created a PHP page that dynamically reads images from a folder and displays them on a gallery page. However, I am facing some issues - I am unable to link an external CSS file and I have to include all the CSS within the HTML. Additionally, I c ...

How to update a value within a deeply nested array in MongoDB and then sort the data

In my document, I have a list of timestamps that are sorted by time: { _id: '1', timestamps: [ { id: '589b32cf-28b3-4a25-8fd1-5e4f86682199', time: '2022-04-13T19:00:00.122Z' }, { id: '781 ...

Display only the static placeholder in Angular 2 multi-select feature

My experience with angular 4 is fairly new and I've recently delved into using the angular multiselect feature with the npm package available here. I've managed to successfully configure it, as well as capture selected and deselected items/event ...

Jumping JavaScript input fields for entering birthdates

I have 3 input text fields in a row to input a date <form> <input type="text" name="day" /> <input type="text" name="month" /> <input type="text" name="year" /> </form> The day and month fields are the main focus. Each ...

The authentication callback function fails to execute within Auth0 Lock

I'm having an issue with logging into my application using Auth0. I have integrated Auth0 Lock version 10.3.0 through a CDN link in my project and am utilizing it as shown below: let options = { disableSignupAction: true, rememberLastLogin: f ...

Having trouble connecting to my MongoDB container using Node.js

I am facing an issue while trying to connect my local mongoDB docker, named "some-mongo", to my NodeJS backend server running on the same computer. The problem arises when attempting to establish the connection using the "mongoose" module. To launch my mo ...

What is the best way to adjust the responsiveness of my AppDrag page for mobile optimization?

My landing page is all set up, but I'm looking to tweak the font sizes and spacing for mobile users. Can these changes be made using design tools instead of digging into the code? ...

How to identify the file type of a document using Node.js

A question posed six years ago about getting file types in Node.js through the File System still attracts attention. The answer from 2012 was once correct but has since been surpassed by a better solution. This raises the need for an updated approach to f ...

Verify if function is returning sessionStorage using jest

Recently, I've been working on creating a jest test for the function below that sets a sessionStorage entry: /** * @desc create authenticated user session * @param {String} [email=''] * @param {Date} [expires=Date.now()] * @param {St ...