简体   繁体   中英

Implementing prompts in text-input

I have a form with some text-inputs: login, password.

If user sees this form the first time, input-texts should "contain" prompts, like "enter login", "enter password".

If user clicks text-input, it's prompt should disappear to allow typing.

I have seen various examples, that uses background image with prerendered text on it.

Those images are appearing with following jQuery:

$("form > :text").focus(function(){
   // hide image
}).blur(function(){
   // show image, if text-input is still empty
   if ( $(this).val() == "" )
      // show image with prompt
});

This approach has following problems:

  • localization is impossible

  • need to pre-render images for various textual prompts

  • overhead with loading images

How do you overcomes such a problems ?

This is commonly called a "placeholder," and actually works in several browsers now.

Check out A Form of Madness: Placeholder Text :

<form>
  <input name="q" placeholder="Search Bookmarks and History">
  <input type="submit" value="Search">
</form>

And for browsers that don't support it, here's a JavaScript (jQuery) shim that will use that text to simulate the same effect: jquery-html5-placeholder-shim . If you include a reference to the shim, just add this to your JavaScript and you're good to go.

$(function(){
    $.placeholder.shim();
});

As to the issue of localization, as long as you're producing HTML with the correct information inside the placeholder attribute you should be fine.

Because Zuul, a .value can be submitted and potentially bypass form completion rules and requirements without the user entering anything at all. A placeholder is a softer value that the form does not recognize as an actual value if left unfocused by the user.

A simple solution that incorporates your answer and addresses the asker's question more directly might be something like this:

This will clear the placeholder text when the field is selected/focused and return placeholder text if deselected with no input present in the field when deselected:

<input type="text" placeholder="1866" onFocus="if (this.placeholder=='1866') this.placeholder = ''" onBlur="if (placeholder=='') this.placeholder='1866'">

This will clear the placeholder text only when a user types in the field, but not before:

<input type="text" placeholder="1492">

This version requires nothing extra to work as expected.

Cheers.

Why do you simplify that just ussing something like:

<input type="text" name="username" value="Your User Name" onfocus="if (this.value=='Your User Name') this.value = ''">

If the user gives focus to that input, it will remove the default text, allowing writing some fresh one :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM