What is the method for displaying the value of a textarea?

I am relatively new to the world of coding, but I have already delved into HTML, CSS, and basic DOM scripting.

My goal is simple - I want to create a comment box where people can leave messages like in a guestbook. However, when I input text and click on 'comment', nothing seems to happen. How can I enable users to type a message and see it displayed below? Any help with this issue would be greatly appreciated!

If anyone has encountered this problem before and knows how to solve it, please share your insights.

function fn1() {
  var str = document.getElementById("text1").value;
  alert("Thank you!");
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: white;
  font-family: sans-serif;
  /*
  background-image: url(guest.jpg);
  background-size: 450px;
  */
}

.container {
  width: 600px;
  border: 2px solid black;
  padding: 15px 10px;
}

.container h2 {
  text-align: center;
  margin-bottom: 15px;
}

textarea {
  height: 25px;
  width: 100%;
  border: none;
  border-bottom: 2px solid gray;
  background-color: transparent;
  margin-bottom: 10px;
  resize: none;
  outline: none;
  transition: .5s
}

.btn button {
  padding: 10px 15px;
  border: none;
  outline: none;
  border-radius: 5px;
  text-transform: uppercase;
  font-weight: bold;
  cursor: pointer;
  color: white;
  background-color: orange;
}

button {
  color: gray;
  background-color: lightgray;
}
<!DOCTYPE html>
<html>

<head>
  <title>Visitor comment</title>
  <link rel="stylesheet" type="text/css" href="visitor.css">
</head>

<body>
  <div class="container">
    <h2>Leave Us a Comment</h2>
    <form>
      <textarea id="text1" placeholder="Add Your Comment"></textarea>
      <div class="btn">
        <button onclick="fn1()" id="btn1">Comment</button>
        <!-- <button>Cancel</button> -->
      </div>
    </form>
  </div>
  <p id="result"></p>
  <script type="visitor.js"></script>
</body>

</html>

Answer №1

There are a couple of important steps you need to take in order to achieve the desired outcome. If you have any questions, do not hesitate to ask for clarification.

Firstly, it is crucial to prevent the form from submitting. This can be achieved by binding a function to the onsubmit event.

Secondly, you will need to add the value of the textbox to the result paragraph dynamically.

Any additional styling requirements should be manageable at your end. In my example, I am using a list but this is not mandatory.

function fn1() {
  let li = document.createElement("LI");
  let text = document.createTextNode(document.getElementById("text1").value);
  li.appendChild(text)
  document.getElementById("result").appendChild(li);
  alert("Thank you!");

}

function submithandler(event) {
  event.preventDefault();
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: white;
  font-family: sans-serif;
  /*background-image: url(guest.jpg);
    background-size: 450px;*/
}

.container {
  width: 600px;
  border: 2px solid black;
  padding: 15px 10px;
}

.container h2 {
  text-align: center;
  margin-bottom: 15px;
}

textarea {
  height: 25px;
  width: 100%;
  border: none;
  border-bottom: 2px solid gray;
  background-color: transparent;
  margin-bottom: 10px;
  resize: none;
  outline: none;
  transition: .5s
}

.btn button {
  padding: 10px 15px;
  border: none;
  outline: none;
  border-radius: 5px;
  text-transform: uppercase;
  font-weight: bold;
  cursor: pointer;
  color: white;
  background-color: orange;
}

button {
  color: gray;
  background-color: lightgray;
}
<!DOCTYPE html>
<html>

<head>
  <title>Visitor comment</title>
  <link rel="stylesheet" type="text/css" href="visitor.css">
</head>

<body>
  <div class="container">
    <h2>Leave Us a Comment</h2>
    <form onsubmit="submithandler(event)">
      <textarea id="text1" placeholder="Add Your Comment"></textarea>
      <div class="btn">
        <button onclick="fn1()" id="btn1">Comment</button>
        <!-- <button>Cancel</button> -->
      </div>
    </form>
  </div>
  <ul id="result"></ul>
  <script type="visitor.js"></script>
</body>

</html>

Answer №2

Here is an alternative JavaScript approach:

const form = document.forms[0];
const textarea = document.getElementById('text1');
const output = document.getElementById('output');

form.onsubmit = () => {
   output.innerHTML = '<li>' + textarea.value + '</li>';
   return false;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining ng-repeat with the float property set to left

I am attempting to create two rows of divs using ng-repeat. Each div is styled with a float: left attribute, and at the end, I add a clearing div with clear: both. <div class="interval" ng-repeat="interval in intervals"> <div class="text-cen ...

Guide on how to execute jasmine tests coded in TypeScript for Node.js applications

I am eager to test my express application developed in TypeScript. I am utilizing jasmine for writing test cases, webpack for bundling TypeScript files to JavaScript, and karma as the test runner. Please locate the following files: // about.service.ts - ...

Received a 502 Bad Gateway Error message following a 2-minute wait for the webpage to load

Greetings, I have been working on creating a small form for my school, and everything was running smoothly until I implemented the function "reorganizeVector()." However, now when I try to test my form (only on this webpage) in a browser, it takes 2-3 minu ...

The JavaScript-set value in a form field is not being transmitted to the PHP script within the $_POST array

Struggling to pass a JavaScript value to a .php script, and then on to a .txt script. It works fine with regular numbers, but when trying with the variable it fails, leaving the .txt file blank. Despite extensive research online, I can't seem to get i ...

Combine Two Values within Model for Dropdown Menu

I am currently facing a situation where I have a select box that displays a list of users fetched from the backend. The select box is currently linked to the name property of my ng model. However, each user object in the list also contains an email proper ...

Aligning angular bootstrap modal window in the center vertically

Is there a way to vertically center a modal window on the screen, regardless of the size of the content being displayed? I'm currently using an image as a modal window in my page, and while I was able to align it horizontally, I'm struggling to g ...

What is the process for utilizing the TypeScript compiler with nodejs?

I have a sample code saved in a file called hello.ts Upon the completion of nodejs setup on Windows, execute the following command to install typescript: npm install -g typescript Is there a way to compile hello.ts directly with node.js? While using "T ...

Is there a way to temporarily halt a jQuery animation for 2 seconds before automatically resuming it, without relying on mouse-over or mouse-out triggers?

With just one scrolling image implemented in jQuery, the logos of clients are displayed continuously in a scrolling box with no pauses. Speed can be adjusted easily, but pausing and then resuming the animation after 2 seconds seems to be a challenge whic ...

Tips for effectively exchanging information among angular services

Currently, I am in the process of refactoring a complex and extensive form that primarily operates within a controller. To streamline the process, I have started segregating related functions into separate modules or services. However, I am grappling with ...

Hide/Show overflow causing a disruption in my perspective

I am puzzled as to why my paragraph is not starting on a new line despite the overflow property set on the previous element. Take a look at my plunker, adjust the overflow property in line 11 to hidden and it will display correctly. When set to visible, i ...

Ways to ensure a form label is accessible via keyboard navigation

My HTML5 form collects user information and processes it upon submission. With the help of the jQuery Validation Plugin, input validation is performed. In case of errors, an error-message-container div is displayed at the top of the screen, listing all err ...

Component loader with dynamic rendering for multiple components

Currently, I am in search of a method to dynamically render components within my Angular application. While exploring various options, I came across the concept of dynamic component loading in Angular (refer to https://angular.io/guide/dynamic-component-lo ...

Ensure that the GraphQL field "x" with type "[User]" includes a selection of subfields. Perhaps you intended to specify "x{ ... }" instead

I am encountering an issue while attempting to execute the following simple query: {duel{id, players}} Instead, I received the following error message: Field "players" of type "[User]" must have a selection of subfields. Did you mean & ...

"Troubleshooting: Jquery Draggable Function Fails to Execute

I'm currently working on a JSP page where I am attempting to make the rows of a table draggable. Despite multiple attempts and combinations, I have been unable to make any elements draggable. The rows are appended after an AJAX call, but still no succ ...

Using jQuery, you can submit a form easily

In my work with Django, I am developing a quiz web application that requires a form submission after answering each question. The questions are displayed correctly, but I am facing an issue when trying to submit the form with the answers. The answers to t ...

Express.js: Initial Request Fails to Retrieve Set Cookie

In my Express.js application, I am facing an issue where setting a cookie in one middleware function results in it being undefined when attempting to access it in the following middleware function on the initial request. Strangely, on subsequent requests, ...

Enhancing User Experience with Load Indicator during State Changes in React Native

I'm facing an issue where the page for displaying a single item is loading slowly - I need to delay the page from loading until the object has changed. After checking the navigation params through console log, I can see that the id changes when each b ...

The functionality of Bootstrap pagination is incompatible with the angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.js library

After reading through this discussion, I have found that in order to resolve an issue, I need to utilize a newer version of ui-bootstrap-tpls.js. However, the downside is that this disables the functionality of bootstrap pagination, which only works with a ...

Can you clarify the meaning of 'this' in an AngularJS controller?

index.html <body ng-controller="StoreController as s"> <h1 ng-click="s.changeValFunc()">{{s.carname}}</h1> <h2>{{s.carname}}</h2> </body> app.js var app = angular.module('store', []); app.controller(& ...

Inform jQuery that the draggable element is in the process of being dragged dynamically

Currently, this issue is a vital component of an ongoing task. Once we can resolve this issue, it will lead to the completion of this and another inquiry. The original objective can be found here: drag marker outside map to html element You can view the ...