Clear Textbox or Input Box on focus using JavaScript or jQuery

← PrevNext →

You can use the onfocus attribute in JavaScript to clear a textbox or an input box when somebody sets focus on the field. If you are using jQuery, then use the .focus() method to clear the field.

JavaScript onfocus Attribute

In the first example here, I am using an inline method with the onfocus attribute to clear a textbox.

<body>
    <input type='text' id='name' value = 'Hello' 
    	onfocus = 'this.value = ""' />
</body>
Try it

The keyword this represents the input field itself (the textbox). You simply have to assign nothing as value.

onfocus = 'this.value = ""'

In most cases, you might have to check a condition before clearing the value in the field. In that case, add a if condition like this.

<body>
    <input type='text' id='name' value = 'Morning' 
        onfocus = 'if (this.value == "Morning") this.value = ""' />
</body>
Try it

If the inline method does not suit your requirement, then you can call a function to clear the input field. For example,

<body>
    <input type='text' id='name' value = 'Enter your name' onfocus = 'clearField (this)' />
</body>
<script>
    function clearField(ele) {
        ele.value = '';
    }
</script>
Try it

Clear fields on focus using jQuery .focus() Method

Alternatively, you can use the jQuery .focus() method to clear an input field, if in your application you are using jQuery.

<!DOCTYPE html>
<html>
<head>
    <title>Clear textbox on focus using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <p>Setting focus on the textbox will clear the value.</p>
 	<input type='text' id='name' value = 'Enter your name' />
</body>
<script>
    $(document).ready(function () {
        $('#name').focus(function () {
            $(this).val('');
        });
    });
</script>
</html>
Try it

There are different ways to do this. I would recommend using JavaScript methods, wherever possible. Its simple and lightweight.

Well, that’s it. Thanks for reading.

← PreviousNext →