user521024
user521024

Reputation: 531

Persistent Placeholder for input and select boxes

I want to have persistent placeholders for input and select boxes.For example,

<input type="text" placeholder="First Name:" />

The input text box will render with placeholder 'First Name:'. Suppose when input is focused and value entered is 'Ram', then Placeholder should show as 'First Name: Ram'.If we delete the Ram, then only 'First Name:' should be there.The similar behavior should exist for Select boxes too.On selecting an option, value should be shown as "First Name: Any" (Any is value selected). Using Jquery is also fine.

Upvotes: 0

Views: 3900

Answers (2)

cuadraman
cuadraman

Reputation: 15164

You could do something like

HTML

<div class="container">
  <input type="text" value="" class="free-typing"></input>
  <input autocomplete="off" value="First Name:" class="persistent-placeholder"/>
</div>

CSS

.container {
   display: block;
   max-width: 600px;
   position: relative;
   height: 36px;
   box-sizing: border-box;
   border: 1px solid gray;
   border-radius: 3px;
   background-color: white;
}

.persistent-placeholder {
   height: auto;
   width: 100%;
   color: silver;
   z-index: 0;
   position: absolute;
   top: 0; bottom: 0;
   left: 0; right: 0;
   background-color: transparent;
   border: none;
   text-indent: 5px;
   line-height: 36px;
}

.free-typing {
  z-index: 1;
   width: 100%;
   background-color: transparent;
   position: absolute;
   top: 0;  bottom: 0;
   left: 0;  right: 0;
   box-sizing: border-box;
   border: none;
   text-indent: 5px;
   line-height: 36px;
   font-size: 18px;
   padding-left: 100px; // this will give you indentation for the placeholder to show
}

For more information I wrote a post on how I achieved a similar effect. https://medium.com/@Cuadraman/how-to-recreate-google-s-input-persistent-placeholder-8d507858e815#.1vs0vyigx

Upvotes: 1

rink.attendant.6
rink.attendant.6

Reputation: 46257

For accessibility, use a <label> element, like this:

<label for='firstName'>First Name:</label>
<input type='text' id='firstName' placeholder='First name'>

Similarly, on <select> elements:

<label for='foo'>Foo:</label>
<select id='foo'>
    <option value='1'>Bar</option>
    <option value='2'>Baz</option>
</select>

You can style the label element to appear as you wish using CSS.

Upvotes: 1

Related Questions