Displaying Specific Output from an Input Field Using JavaScript
Let's learn how to display specific output for an input field. This is a common task when working with HTML forms and user input.
First, let's create a simple HTML form with an input field and a button. The user will enter their input in the field, and when they press the button, we'll display a specific output.
<!DOCTYPE html> <html> <body> <h2>JavaScript Input Output Example</h2> <input type="text" id="myInput" value="" /> <button onclick="displayOutput()">Submit</button> <p id="output"></p> </body> </html>
In this HTML code, we have an input field with the id myInput
, a button that calls a JavaScript function displayOutput()
when clicked, and a paragraph with the id output
where we'll display our output.
Next, let's add the JavaScript code that will take the user's input and display the output.
<script> function displayOutput() { var input = document.getElementById("myInput").value; var output = document.getElementById("output"); if (input === "Hello") { output.innerHTML = "World!"; } else { output.innerHTML = "You didn't say hello."; } } </script>
In this JavaScript code, we first get the value of the input field and the output paragraph using their ids. We then check if the input is equal to "Hello". If it is, we set the output to "World!". If it's not, we set the output to "You didn't say hello.".
And that's it! This is just a basic example, and you can expand on this to handle more complex scenarios, such as validating the input or displaying different outputs based on different inputs.
Get my free, weekly JavaScript tutorials
Want to improve your JavaScript fluency?
Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.
Join today, and level up your JavaScript every Sunday!
Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.