如何在单击文本框时清除文本框

How to clear a text box when clicked on it?

本文关键字:文本 清除 单击      更新时间:2023-09-26

我使用这个JS来清除文本框,当用户点击它,所以这工作得很好,并清除页面中的所有文本框,我想只清除搜索文本框搜索. .我该怎么做呢,其他文本框不应该被清除,只有这个搜索文本框应该被清除,当我点击它。

  <script type="text/javascript">
        $(function () {
            $('input[type=text]').focus(function () {
                $(this).val('')
            });
        });
    </script>

还有一个问题

我有一个面板有几个文本框,我如何设置焦点在一个特定的文本框

 <asp:TextBox ID="txt_Name" runat="server" />

通过ID或其他属性选择TextBox

<asp:TextBox id="txt_Search" runat="server" />

然后通过它的唯一客户端ID选择TextBox

$('#<%=(txt_Search.ClientID)%>').focus(function() { $(this).val(''); });

为明确值- $('#yourTextBox').val('');

For set focus - $('#yourTextBox').focus();

我认为使用id值不是最好的主意,因为.net可能会在运行时改变id

eg MainContent_txt_Name

你可以这样做

<asp:TextBox ID="txt_Name" CssClass="myText" runat="server" />
<script type="text/javascript">
        $(document).ready(function () {    
           $('.myText').click(function() {
                $(this).val('')
            });    
        });
</script>

代替$('input[type=text]')$('search-box-id')

您所需要的就是为搜索框指定id,尝试检查您的元素,或者查看源代码以获得正确的id,因为id是由ASP生成的。. NET web表单,或者您可以添加自定义属性,如rel="search-box"

这是javascript

$(document).ready(function() {
  //for id
   $('#id_of_text_box').focus(function() { $(this).val(''););
  //for rel attribute
   $('input[rel="search-box"]').focus(function() {$(this).val(''););
});

我会使用HTML5的defaultvalue属性返回到这个jquery方法:

http://unwrongest.com/projects/defaultvalue/

另一个选择,沿着一个稍微不同的路线,使用JQuery文本框水印组件。这已经被创建来做你所要求的,并将重新填充当他们点击离开文本框,但后端永远不会看到值。省去了你自己动手的麻烦!

http://code.google.com/p/jquery-watermark/