jquery - in keyDown erase text from input

和自甴很熟 提交于 2019-12-10 21:18:45

问题


I have a input box that i have some text in site

<input type="text" value="Enter Name"/>

Now i need to add that when the user starts typing in something (enters the first letter), my text will disappear and he will be able to enter the input he wants.

I tried doing:

$('#input').keypress(function () {
                $(this).val("");
            });

But then the user can only enter one letter cuz it keeps on deleting the text.

How can this be done?

Thanks


回答1:


You can do this by using a placeholder

Demo: http://jsfiddle.net/9VhYZ/

Some browser doesn't yet support this, adding a fallback could also be a good idea to support it cross browser: http://davidwalsh.name/html5-placeholder

UPDATE: You can do what you ask for like this: http://jsfiddle.net/9VhYZ/1/

$('#input').one("keydown", function () {
    $(this).val("");
});



回答2:


Often this technique is called Ghosting. You can use the placeholder attribute plus progressive enhancement. Often I like to do it by using a class ghostInput and having it globally applied on page load so I can add ghost properties to elements simply by appending the global class.

<input type="text" value="Enter Name" placeholder="something" class='ghostInput'/>

$(function() {
  $(".ghostInput").focus(function() {
    if ($(this).val() == $(this).attr("placeholder")) {
      $(this).val("");
    }
  }).blur(function() {
    if ($(this).val() == "") {
      $(this).val($(this).attr("placeholder"));
    }
  });
});

Often with this you'll want to add and remove another class from the input to make the text appear a little bit lighter which is fairly easy. Just remove it on focus() and add it on an empty blur().




回答3:


I would recommend using the HTML5's placeholder attribute instead of JavaScript:

<input type="text" value="Enter Name" placeholder="something"/>

Be warned - it is not supported everywhere, but if you have the luxury of ignoring older browsers then this is definitely the solution to go with.




回答4:


You're implementing the default value of a textbox.

You have two options:

  • A plugin: http://plugins.jquery.com/project/default-value
  • HTML5's placeholder="Value" attribute.

HTML5 isn't supported by all browsers, so I'd try both.



来源:https://stackoverflow.com/questions/7968750/jquery-in-keydown-erase-text-from-input

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