如何在第一次聚焦时清除文本框? [英] how to clear textbox when it first comes into focus?

查看:81
本文介绍了如何在第一次聚焦时清除文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试清除文本框,当它第一次成为焦点时,就是这样。每当它出现焦点时我都可以清除文本框,但这会变成一个问题。我只是希望它能在第一次成为焦点时清除。

I'm trying to clear a textbox when it first comes into focus and that's all. I can clear the textbox whenever it comes into focus but this is turning into a problem. I just want it to clear when it first comes into focus.

因此,当页面加载时,文本框会显示在此搜索 - 一旦用户点击内部,在此搜索消失,文本框变为空白。用户可以继续键入他们的搜索查询。

So when the page loads, the textbox says "search here" -- once the user clicks inside, "search here" disappears and the textbox goes blank. The user can keep typing their search query.

但是我的代码,如下所示,只是不断清除文本框。有什么想法?

But my code, as seen below, just keeps clearing the textbox. Any ideas?

    $('input[type=text]').focus(function() {
      $(this).val('')
});


推荐答案

这会清除焦点上的默认文本并将其放回在模糊。如果以不同的默认值键入新文本,则不再清除输入。通过单击外部并输入几次来测试它。然后输入新文本并执行相同操作。

This clears the default text on focus and puts it back in on blur. If a new text is typed in different then default value, it no longer clears the input. Test it out by clicking outside and input few times. Then type in new text and do the same.

$('.text').focus(function() {
    if (this.value == this.title) {
        $(this).val("");
    }
}).blur(function() {
    if (this.value == "") {
        $(this).val(this.title);
    }
});

这篇关于如何在第一次聚焦时清除文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆