Show Data Using Text Box in TypeScript


Data representation is crucial in software development, and it is essential to present data in a user-friendly way with the increasing demand for web-based applications. Text boxes are one of the ways to do so. Text boxes provide an easy way to display data to users in a structured and presentable way.

This tutorial will provide a comprehensive guide on using text boxes in TypeScript to show data effectively. We will cover what text boxes are, provide syntax and algorithms for working with text boxes, and give multiple examples to illustrate how to use text boxes.

What are Text Boxes in TypeScript?

Text boxes are a common and useful input element in web development. They allow users to input or view data in a structured and user-friendly way. In TypeScript, creating and working with text boxes is relatively straightforward. This section will cover the basics of text boxes in TypeScript, including creating text boxes, text box properties, events, and validation.

To create a text box in TypeScript, we use the HTML input element with the type attribute set to "text". We can add attributes to customize the text box, such as a placeholder, value, and ID.

Here is an example of creating a text box in TypeScript −

const textBox = document.createElement("input");
textBox.type = "text";
textBox.placeholder = "Enter your name";
textBox.value = "John Doe";
textBox.id = "nameInput";
document.getElementsByTagName('body')[0].appendChild(textBox);

Output

Properties of Text Boxes in TypeScript

Text boxes have several properties that we can use to customize their appearance and behavior. Some of the common properties of text boxes include −

  • value − the text displayed in the text box

  • placeholder: a hint or example text displayed in the text box when it is empty

  • readOnly − a Boolean value that determines whether the text box is editable or not

  • disabled − a Boolean value that determines whether the text box is enabled or not

  • maxLength − the maximum number of characters allowed in the text box

Here is an example of setting some properties of a text box in TypeScript −

const textBox = document.createElement("input");
textBox.type = "text";
textBox.placeholder = "Enter your email";
textBox.readOnly = true;
textBox.disabled = true;
textBox.maxLength = 50;
document.getElementsByTagName('body')[0].appendChild(textBox);

Output

Events in Text Boxes in TypeScript

Text boxes also have several events we can use to detect user actions and respond accordingly. Some of the common events of text boxes include −

  • focus − triggered when the text box receives focus

  • blur − triggered when the text box loses focus

  • input − triggered when the value of the text box changes

  • change − triggered when the value of the text box changes and focus is lost

Here is an example of adding an event listener to a text box in TypeScript −

const textBox = document.createElement("input");
textBox.type = "text";
textBox.placeholder = "Enter your age";
textBox.addEventListener("input", (event) => {
   console.log(`Value changed to ${event.target.value}`);
});

Output

Validation in Text Boxes in TypeScript

Validation is a critical aspect of working with text boxes. We must ensure that the user input meets certain criteria before processing it. In TypeScript, we can use several methods to validate text boxes, such as regular expressions, custom functions, and built-in validation attributes.

Here is an example of using a regular expression to validate a text box in TypeScript −

TypeScript Code

const input = document.getElementById('email') as HTMLInputElement | null;
const emailError = document.getElementById('email-error');
input?.addEventListener('input', function (event) {
   const target = event.target as HTMLInputElement;
   const value = target.value;
   const regex = /^\S+@\S+\.\S+$/;
   if (!regex.test(value)) {
      input.setCustomValidity("Please enter a valid email address.");
      emailError.style.color = "red"
   } else {
      input.setCustomValidity("Perfectly Valid Email");
      emailError.style.color = "green"
   }
const validationMessage = input.validationMessage;
emailError.textContent = validationMessage;
});

HTML Code

<!DOCTYPE html>
<html>
<head>
   <title>Document</title>
   <script defer src="./index.js"></script>
</head>
<body>
   <input type="text" id="email" placeholder="Enter your email">
   <div id="email-error"></div>
</body>
</html>

Output

Examples of Using Text Boxes in TypeScript

Using Text Boxes for User Input and Data Collection

Text boxes can be used for user input and data collection. In TypeScript, we can use the input event to detect when the user types something into the text box.

let nameTextBox = document.getElementById("name") as HTMLInputElement;
nameTextBox.addEventListener("input", () => {
   console.log("User entered: " + nameTextBox.value);
});

Output

Displaying Dynamic Data in Text Boxes

Text boxes can also be used to display dynamic data that is fetched from the backend or updated in real time. Let's consider an example where we want to display the current time in a text box.

In the code below, we create a text box using the document.createElement method and set its type to "text" using the type property. We then define a function called updateTextBox that fetches the current time using the toLocaleTimeString method and sets the value of the text box to the current time. We use the setInterval method to update the text box every second.

let dynamicTextBox = document.createElement("input");
dynamicTextBox.type = "text";
function updateTextBox() {
   let currentTime = new Date().toLocaleTimeString();
   dynamicTextBox.value = currentTime;
}
// Update the text box every second
setInterval(updateTextBox, 1000);
document.getElementsByTagName('body')[0].appendChild(dynamicTextBox)

Output

Conclusion

In conclusion, text boxes are a powerful tool for displaying and collecting data in TypeScript. In this tutorial, we covered the basics of TypeScript and text boxes, provided syntax and algorithms for working with text boxes, and gave multiple examples to illustrate how to use text boxes effectively. We saw how text boxes can be used to display static and dynamic data

Updated on: 04-Sep-2023

944 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements