How to remove default value of input on focus

2019-03-10 16:57发布

I have an input box that has default value text assigned to it. How can I remove this text when the user focuses on the field::

CoDE

<input type="text" name="kp1_description" value="Enter Keypress Description">

9条回答
姐就是有狂的资本
2楼-- · 2019-03-10 17:39
<input type="text" id="anything" placeholder="enter keypress description">

i think this will help

查看更多
家丑人穷心不美
3楼-- · 2019-03-10 17:41

Don't do it this way. Use a jQuery watermark script: http://code.google.com/p/jquery-watermark/

$("input[name='kp1_description']").watermark("Enter Keypress Description");

There are a lot of things you have to account for if you do it manually. For instance, what happens when the text box loses focus? If there's no value, you'd want to readd your helper text. If there is, you'd want to honor those changes.

Just easier to let other people do the heavy lifting :)

查看更多
Bombasti
4楼-- · 2019-03-10 17:41
$('input, textarea').each(function () {
    var Input = $(this);
    var default_value = Input.val();

    Input.focus(function() {
        if(Input.val() == default_value) Input.val("");
    }).blur(function(){
        if(Input.val().length == 0) Input.val(default_value);
    });
});
查看更多
我想做一个坏孩纸
5楼-- · 2019-03-10 17:45

var defaultForInput = "abc";

<input id="myTextInput" type="text" placeholder=defaultForInput />


When submitting your form, check if the input(id="myTextInput") value is the 'empty-string', if so substitute it with (defaultForInput).

查看更多
Explosion°爆炸
6楼-- · 2019-03-10 17:49
$(document).ready(function(){
    var Input = $('input[name=kp1_description]');
    var default_value = Input.val();

    Input.focus(function() {
        if(Input.val() == default_value) Input.val("");
    }).blur(function(){
        if(Input.val().length == 0) Input.val(default_value);
    });
})​

That should do it.

Updated, Forgot that focus does not have a 2nd parameter for the focus-out event because there is none, it has to be chained with blur:

http://jsfiddle.net/hDCsZ/

you should also think about creating your own function for this such as:

$.fn.ToggleInputValue = function(){
    return $(this).each(function(){
        var Input = $(this);
        var default_value = Input.val();

        Input.focus(function() {
           if(Input.val() == default_value) Input.val("");
        }).blur(function(){
            if(Input.val().length == 0) Input.val(default_value);
        });
    });
}

Then use like so

$(document).ready(function(){
    $('input').ToggleInputValue();
})​
查看更多
戒情不戒烟
7楼-- · 2019-03-10 17:51

The Super Duper Short Version

$('#input_id').focus(function() {
    $(this).val("");
});
查看更多
登录 后发表回答