Hello Friends Today, through this tutorial, I will tell you How to Write Program word counter calculator using JavaScript with HTML? You can create a word counter calculator using JavaScript and HTML without a submit button by using the `input` event to detect changes in the input field dynamically. Here’s how you can implement it:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Word Counter Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
label {
display: block;
margin-bottom: 8px;
}
input {
width: 100%;
padding: 8px;
margin-bottom: 16px;
box-sizing: border-box;
}
</style>
</head>
<body>
<h2>Word Counter Calculator</h2>
<label for="text">Enter Text:</label>
<input type="text" id="text" placeholder="Enter text here">
<p>Word count: <span id="wordCount">0</span></p>
<script>
// Get the input element
const textInput = document.getElementById('text');
// Get the span element where word count will be displayed
const wordCountDisplay = document.getElementById('wordCount');
// Add input event listener to input element
textInput.addEventListener('input', function() {
// Get the text content of the input element and split it into words
const words = this.value.trim().split(/\s+/);
// Display the count of words
wordCountDisplay.textContent = words.length;
});
</script>
</body>
</html>
In this code:
1. An `input` event listener is added to the text input field.
2. Whenever the user types or removes text in the input field, the `input` event is triggered.
3. Inside the event handler function, the text content of the input field is trimmed to remove leading and trailing spaces.
4. The trimmed text is then split into an array of words using a regular expression (`\s+` matches one or more whitespace characters).
5. The length of the array (number of words) is then displayed in the `span` element with the id `wordCount`.
Example:-
Word Counter Calculator
Word count: 0