开发者

JQuery Empty A Textfield When I click in it

How do I empty a textfield (html form) if I click in it to write something.

Pseudo Code:

On click #searchform
Erase String in #sear开发者_如何学Gochform


$('#searchform').click(function() { $(this).val('') })


Try it here

$('#searchform').click(function() { 
    if ($(this).val() == 'Enter search term') {   
        $(this).data('original', $(this).val()).val('');
    }
});

$('#searchform').blur(function() { 
    if ($(this).val() == '') {   
        $(this).val($(this).data('original'));
    }
});

EDIT As of now you should use the placeholder attribute and if you want, use the above as a polyfill for missing placeholder support.

if (!('placeholder' in document.createElement('input'))){
    $('input[placeholder]').each(function() {
        $(this).placeholder();
    });
}

And turn the original code into a plugin for easy use (with some small mods).

jQuery.fn.placeholder = function() {
    return this.each(function() {
        var value = $(this).attr('placeholder');
        jQuery(this).val(value).addClass('placeholder');
        jQuery(this).focus(function() {
            if (jQuery(this).val() == value) {
                jQuery(this).val('').removeClass('placeholder');
            }
        });

        jQuery(this).blur(function() {
            if (jQuery(this).val() == '') {
                jQuery(this).val(value).addClass('placeholder');
            }
        });
    });
};


I'd recommend you using the HTML5 placeholder attribute. For example:

<input type="text" placeholder="some default string if empty" />

This will work with most of the newest browsers and for older ones there is a workaround jQuery plugin. Here is the link to the placeholder plugin.

And then you simply call:

$('input[placeholder]').placeholder();


If you are wanting to clear a default value from a field such as "Enter Search Term" I use the following code:

function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
} 

and then on my input field I add:

onfocus="clearText(this)"

So it would be:

<input type="text" name="username" value="enter your name here"  onfocus="clearText(this)">
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜