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 achie开发者_运维知识库ved?
just get element using
function name()
{
document.getElementById('elementid').value = "";
}
you can call this function on onfocus event of textbox and clear the value
It sounds like you're trying to use a "watermark" (a default value that clears itself when the user focuses on the box). Make sure to check the value before clearing it, otherwise you might remove something they have typed in! Try this:
<input type="text" value="A new value" onfocus="if(this.value=='A new value') this.value='';">
That will ensure it only clears when the value is "A new value".
<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';}" />
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 set empty string
<input type="text" id="textId" value="A new value">
document.getElementById('textId').value = '';
use sth like
<input type="text" name="yourName" placeholder="A new value" />
Simple one
onfocus="this.value=''" onblur="if(this.value==''){this.value='Search...';}"
If using jQuery is acceptable:
jQuery("#myTextBox").focus( function(){
$(this).val("");
} );
Give this in input tag of textbox:
onClick="(this.value='')"
<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.
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';">
<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';"/>
Your HTML code,
jquery code,
$("#textboxID").val('');
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)
精彩评论