John
John

Reputation: 487

How to clear text box value when user clicks inside it

<asp:TextBox ID="Txt_search" runat="server">Group Name..</asp:TextBox>

I want to clear the text inside the text box when user clicks inside the text box to enter the keyword to search. How do I do that?

Upvotes: 0

Views: 8550

Answers (5)

johnny
johnny

Reputation: 19735

with jquery:

$(function() {

    $('input[type=text]').focus(function() {

           $(this).val('');
      });

 });

from: How to clear a textbox onfocus?

Upvotes: 3

scartag
scartag

Reputation: 17680

Since you are using asp.net webforms, i think you'll be better off using the AjaxControlToolkit specifically the TextBoxWaterMarkExtender control.

See sample code below.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:TextBoxWatermarkExtender ID="TextBox1_TextBoxWatermarkExtender" 
                    runat="server" Enabled="True" TargetControlID="TextBox1" 
                    WatermarkText="Group Name ...">
                </asp:TextBoxWatermarkExtender>

Upvotes: 0

Amir Ismail
Amir Ismail

Reputation: 3883

using jquery to clear textbox on focus and set it back with default on blur

$(document).ready(function(){
  $('#<%=Txt_search.ClientID%>')
    .focus(function(){  
      if($(this).val()=='Group Name..')
      {
         $(this).val('');
      }
  })
   .blur(function () {
            if ($(this).val() == '') {
                $(this).val('Group Name..');
            }
        });
});

Demo

Upvotes: 0

Praveen
Praveen

Reputation: 1449

I guess you could do that easily using jQuery something like below.

    $('#<%=Txt_search.ClientID%>').click(function() {
         $(this).val("");
    });

Upvotes: 0

John Hartsock
John Hartsock

Reputation: 86872

The script below handles both the onfocus and onblur events removing your default "Group Name.." when focused and adding it back if the user moves off the field without changing anything.

<script type="text/javascript">
  var txtsearch = document.getElementById("Txt_search");
  txtsearch.onfocus = function () {
    if (this.value == "Group Name..") {
      this.value = "";
    }
  };

  txtsearch.onblur = function () {
    if (this.value.length == 0) {
      this.value = "Group Name...";
    }
  }
</script>

Upvotes: 1

Related Questions