开发者

how to blank the textbox on keypress

Hii everyone I m new in all this and I am having a problem.I hope anyone here could help me. I have an inputbox which by default have the value as 'ENTER YOUR NAME' and that value remains even开发者_如何学Go on focus.But what I want is that when the user presses any word the default value should be removed and that value should get entered which he/she is typing.

Any help is appreciated.

Thanks in Advance, Megha.


If you want simple HTML, not HTML5 and not jQuery, add the following to the HTML tag:

onfocus="if (this.value === 'ENTER YOUR NAME') this.value = ''"

replace ENTER YOUR NAME with whatever you want.


Use Placeholder attribute for this

like this :

<input  placeholder="ENTER YOUR NAME" type='text'>

But it work only in latest browsers with HTML5 support


Works in older browsers, requires javascript:

<input type="text" value="ENTER YOUR NAME" onblur="if(this.value === '') this.value = 'ENTER YOUR NAME';" onfocus="if(this.value === 'ENTER YOUR NAME') this.value = '';">

Example: http://jsfiddle.net/q4xKC/

Works in newer browsers (http://caniuse.com/#search=placeholder), requires HTML5:

<input type="text" placeholder="ENTER YOUR NAME">

Example: http://jsfiddle.net/m65ea/

To your update:

Read css/javascript form onfocus placeholder text still there, on typing disappear


You asked for a method to do this on a key press, and all the other answers currently only show you how to do it on focus or blur, so unless I've misunderstood the question, you actually want something like this:

document.getElementById("example").onkeydown = function(e) {
    if(this.value == "Enter something") {
       this.value = "";   
    }
}

This will require you to give your input an id, in this case "example":

<input type="text" id="example">

Here's a working example of the above code.


Firstly make sure that you add the value using javascript, don't include it in your markup...otherwise anyone without javascript will have to delete the text manually, which isn't very user friendly (unless you want that behaviour ofc).

So you can populate it on document.ready, and specific to your requirements of removing it on the key press rather than when the field gets focus, you can use something like this:

$(document).ready(function() {
  $("#nameField").val("ENTER YOUR NAME");
   $("#nameField").keypress(function() {
    if($(this).val() == "ENTER YOUR NAME") {
      $(this).val("");
    }
  });
});

P.S. if you wanted to ensure it was a word character then test the event data for the range of characters you want to remove the current content.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜