[javascript] How to clear a textbox using javascript

I have a

<input type="text" value="A new value">

I need a javascript method to clear the value of the textbox when the focus is on the textbox.

How can this be achieved?

This question is related to javascript

The answer is


use sth like

<input type="text" name="yourName" placeholder="A new value" />


<input type="text" name="yourName" value="A new value" onfocus="if (this.value == 'A new value') this.value =='';" onblur="if (this.value=='') alert('Please enter a value');" />

Onfous And onblur Text box with javascript

   <input type="text" value="A new value" onfocus="if(this.value=='A new value') this.value='';" onblur="if(this.value=='') this.value='A new value';"/>

For my coffeescript peeps!

#disable Delete button until reason is entered
$("#delete_event_button").prop("disabled", true)
$('#event_reason_is_deleted').click ->
    $('#event_reason_is_deleted').val('')
    $("#delete_event_button").prop("disabled", false)

<input type="text" value="A new value" onfocus="this.value='';">

However this will be very irrigating for users that focus the element a second time e.g. to correct something.


Your HTML code,

jquery code,

$("#textboxID").val('');


Simple one

onfocus="javascript:this.value=''" onblur="javascript: if(this.value==''){this.value='Search...';}"

<input type="text" value="A new value" onfocus="javascript: if(this.value == 'A new value'){ this.value = ''; }" onblur="javascript: if(this.value==''){this.value='A new value';}" />

If using jQuery is acceptable:

jQuery("#myTextBox").focus( function(){ 
    $(this).val(""); 
} );

For those coming across this nowadays, this is what the placeholder attribute was made to do. No JS necessary:

<input type="text" placeholder="A new value">

just get element using

   function name()
   {  
   document.getElementById('elementid').value = "";
   }

you can call this function on onfocus event of textbox and clear the value


Use the onfocus and onblur events like this:

<input type="text" name="yourName" value="A new value" onfocus="if (this.value == 'A new value') this.value = '';" onblur="if (this.value == '') this.value = 'A new value';">

Give this in input tag of textbox:

onClick="(this.value='')" 

just set empty string

    <input type="text" id="textId" value="A new value">
    document.getElementById('textId').value = '';