In this tutorial we will learn how to Clear Input Field on Button Click using JavaScript. For this we can use onclick attribute and .value property.
Table of Contents
HTML Code
HTML Code is given below, we have a input tag and a button tag with onclick event to trigger the JavaScript function.
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<title>Clear Input Field on Button Click using JavaScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<input id='input' type="text">
<button onclick="clearField()">Clear It</button>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code given below.
<script>
function clearField()
{
document.getElementById('input').value='';
}
</script>
On button click, function will be executed which will clear the input field value. This is done by assigning empty string to the input field using .value property.
Demo
Video Tutorial
Watch video tutorial on this topic.