Javascript text input fields that display instruction (placeholder) text

痴心易碎 提交于 2019-12-03 09:30:31

问题


What's the best way to have a text input field that displays instructions of what to enter in that field in gray. When you focus on that input field, the gray instruction text disappears and your input text appears black. If you erase your input text and focus away from that input, then the instruction gray text reappears.

I've tried implementing this with jQuery, but I get all kinds of weird issues with different browsers. Sometimes when you go back a screen, the instruction text becomes black and no longer disappears, issues like that.

Is there a standard javascript library for this? I can't find any!

Oh, and the instruction text can't be an image because it has to be available in different languages depending on the browser's language preference.


回答1:


You can use watermark plugin in jquery.use this link.

example

 $(this).Watermark("your instructions");



回答2:


You don't need javascript for this.

HTML5:

<input type="text" id="email" name="email" placeholder="Enter your email address">

This works in modern browsers. If you add modernizr.js to your page then it'll work in all browsers.




回答3:


html

<input type="text" id="user" class="textbox default" value="Enter login name">
<input type="password" id="pass" class="textbox">

jQuery

$(function(){
  $('.textbox').focus(function(){
    if (this.value == this.defaultValue) {
        this.value = '';
        $(this).removeClass('default');
    };
  }).blur(function(){
    if (this.value == '') {
        this.value = this.defaultValue;
        $(this).addClass('default');
    };
  });​
});

demo




回答4:


Make the input transparent and put the text behind it. Check the value onload, onblur to decide if the text should be visible or not. Make it invisible onfocus.

For example: http://dorward.me.uk/tmp/label-work/example.html (you just need to style the label and input with different foreground colours)




回答5:


Look at this one: http://fuelyourcoding.com/scripts/infield/




回答6:


placeholder code - name

name of the variable is,

var name=$("#con-name");
var nameval="Enter your name";



name.val(nameval);
name.focus(function(){  
     if (this.value == nameval ) { 
         this.value = ''; 
     }; 
    }).blur(function(){ 
         if (this.value == '') {    
         this.value = nameval;  
    };  
 });
 //submit to clear code
 $("#sub_con_page").click(function() {  
    if(name.val()==nameval) { 
       name.val(""); 
     } 
 });

DEMO LINK




回答7:


<input type="text" name="myText" value="Enter Name" style="color:gray" onfocus="this.value=''">


来源:https://stackoverflow.com/questions/3446269/javascript-text-input-fields-that-display-instruction-placeholder-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!