In this tutorial we will learn how to Clear Input Field on Focus using JavaScript. For this we can use onfocus attribute, this keyword and .value property.
Table of Contents
HTML Code
HTML Code is given below, we have a input tag with onfocus event attribute which will trigger the JavaScript function to clear input value.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Clear Input Field on Focus using JavaScript</title>
</head>
<body>
<input type="text" onfocus="myFunction(this)" value="Hello World!">
</body>
</html>
JavaScript Code
Take a look at the JavaScript code given below.
<script>
function myFunction(event){
event.value='';
}
</script>
On focus event, the JavaScript function will assign empty string to input value which will clear the current value.
Demo
Video Tutorial
Watch video tutorial on How To Clear Input Field on Focus using JavaScript.