What is the best method for combining multiple lines into separate div or span tags using this text input field?

Is it possible to merge multiple lines into different span tags using a text box?

There is a text box that allows me to insert new div/span class content, right? However, every time I want to add a new class, I have to enter a new line in the text box and press send. What I want now is to have 10 lines of content together with line breaks when pressing Enter.

For example:
My Line 1 is here
My Line 2 is here
My Line 3 is here
My Line 4 is here
My Line 5 is here
My Line 6 is here
My Line 7 is here
My Line 8 is here
...and so on

Then, I would like to copy all 10 lines into the text box at once, press send, and have each line added in a different div/span class instead of all in one class with the < br > tag as it currently works.

Please help me improve my code. Love you, helper, and thanks in advance

Answer №1

I made some enhancements and streamlined your code below. It accomplishes the same tasks as what I believe your original code intended.

Just to note, I used .split("\n") to separate your input based on each newline character and then processed it accordingly.

Additionally, you mentioned inserting a div/span, but your code did not actually create a span tag. I have adjusted my code to include that functionality for you.

const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;

sendButton.addEventListener('click', function() {
  // split the textarea entries into an array
  let lines = (textArea.value).split("\n");

  // iterate over each line, creating a div/span and inserting into the DOM
  lines.forEach( (line) => {
    let encodedLine = encodeHtmlEntity(line);
    let newElement = `<div class="me"><span>${encodedLine}</span></div>`;
    innerDiv.innerHTML += newElement;
  });
  
  // reset the textarea
  textArea.value = '';

});

function encodeHtmlEntity(input) {
  var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
    return '&#' + i.charCodeAt(0) + ';';
  });

  return output;
}
<div id="inner">
  <div class="incoming">
    <div class="them">Lorem
    </div>
  </div>
  <div class="outgoing">
    <div class="me">Lorem ipsum
    </div>
  </div>
</div>

<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>

Answer №2

If you want to separate each text using the String.prototype.split() method and split them by \n (new line) into an array, then iterate over each element using Array.prototype.forEach(), you can use the following code example:

submitButton.addEventListener('click', function () {
  inputField.value.split('\n').forEach((text) => {
    const message = new MessageBuilder().createMessage(text);
    container.appendChild(message);
  });
  inputField.value = '';
});

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

Is it possible to fetch all the content contained within each set of <p> and </p> tags within a specific ID?

I've been trying to extract text between two specific <p> tags in HTML, but my code is only returning the text between a single tag. Here's what I have so far: > var myHTMLString = try String(contentsOf: myURL, encoding: .as ...

How to Dynamically Retrieve Keys from JSON Array in Javascript

Could you lend me your expertise by answering a query of mine? Here is a JSON array that I currently have: [{"A":20,"B":32,"C":27,"D":30,"E":40}] My goal is to pull out the keys (A, B, C, D, E) from this JSON array rather than the values. While I have m ...

How to automatically adjust select view in AngularJS as model value is updated

My select element is structured as follows: <select data-ng-model="transaction.category" class="form-control" data-ng-options="category.name group by category.parent for category in categories" required> </ ...

Update the index of each list object and then add them to the Angular controller

Currently, I am working on integrating Spring with AngularJS. In my setup, I have a Spring controller returning a List object to the Angular controller. When I print the List in the Spring controller console, it appears as follows: [org.com.pro.dto.MyDTO ...

The function useNavigate in React Router DOM is failing to correctly redirect the page

When a user tries to register, the code below is supposed to redirect them from the registration screen to the login screen. Despite successfully registering in the database, submitting the form still results in an error message "Registration failed!" with ...

How does the URL play a role in asynchronous functions when it comes to web scraping?

Currently, I am diving into web scraping and encountered a scenario that has left me puzzled regarding the arrow key function. I am struggling to comprehend why the URL is used twice and how it actually functions. Although I recognize this involves advance ...

Placing the jQuery/javascript source pages right before the closing body tag

Multiple plugin instructions recommend placing the javascript/jQuery source right before the closing body tag. I wondered why this advice is given, but couldn't find a clear explanation for it. In my experience, placing the src file anywhere in the s ...

Is it possible to align an entire column to the right in the Material UI Data Grid?

I'm currently exploring Material UI and grappling with a specific challenge. Is there a method within Material UI to create a Data Grid with two columns, one left-aligned and the other right-aligned? I've managed to align the headers as desired, ...

Error: Vue.js is unable to find the reference for "_vm.KisanData" and throws a TypeError

I need assistance in fixing an error that I am encountering. The issue arises in this method where I am using KisanData, but I am unable to resolve it. const API_URL = "http://localhost:3000/User"; export default { name: "home", info(){ ...

The TypeScript datatype 'string | null' cannot be assigned to the datatype 'string'

Within this excerpt, I've encountered the following error: Type 'string | null' cannot be assigned to type 'string'. Type 'null' cannot be assigned to type 'string'. TS2322 async function FetchSpecificCoinBy ...

Passing an object through a JQuery hyperlink

I am currently utilizing socket.io to receive a list of objects. I then iterate through them in order to generate links. My challenge is figuring out how to pass the object through the link for display when a user selects one. socket.on('result' ...

I am currently encountering an issue with a code snippet that is not performing as anticipated and require clarification

import React, {useEffect, useState} from 'react'; export function App(props) { let [state, setState] = useState(2); console.log('outside', state); useEffect(()=>{ document.querySelector('.btn').addEventListener( ...

Adjust the color of additional SVG paths upon hovering

I have the following code snippet. .icon {stroke-width: 0; stroke: currentColor; fill: currentColor;} a {color: red} a:hover {color: pink} a:hover circle {fill: green !important; color: orange} a:hover path {fill: blue !important} <a href=""> ...

Unable to send a response once the status has been set

I have created a route in my Express application to handle form submissions. I am facing an issue with setting a status and sending a response when an error occurs during the form processing. In the front-end, I am using FormData() and in the back-end, I&a ...

The background is obscured from view because of its current positioning

The issue I am facing is that the background color of the <ol> list is not showing correctly. This problem arose after I floated the label to the left and the input to the right. How can I resolve this? The desired outcome should be: My current resu ...

The Vue.js checkbox linked to a v-model with a value set to false is currently marked as

I'm attempting to create a to-do list resembling the Eisenhower matrix, but I'm encountering an issue with v-bind and v-model being triggered incorrectly. How can I resolve this bug? https://i.sstatic.net/iIhqR.png Code inspiration from Vue.js T ...

Generating fresh dynamic IDs using JavaScript

I'm working on a piece of code that generates a grid-like arrangement of chocolate pieces based on user input for the dimensions. I want each chocolate piece to have its own unique ID (like imgPos1, imgPos2, etc.), but I'm struggling to implement ...

What could be causing my RestFul API built with express and nodejs to crash every day?

I am facing an issue with my RESTful API built using Express and Node.js. The API crashes every time it runs. I have a function that updates the date in the URL to the current datetime. I suspect that this constant update might be causing the API to crash ...

Simple guide to identifying when the content of a dropdown option changes using jQuery

I am seeking a solution for detecting changes in the options of a dropdown field that are updated dynamically. Is there a method to capture an event each time the set of options within the dropdown is modified? I am not looking to track individual option ...

"Rotated element in Opera does not maintain event functionality when positioned outside its

Make sure to test this example on Opera (version 12.02) by clicking this link. In Opera, try clicking the red box inside the blue box (event is triggered), then click the red box outside the blue box (event isn't triggered). The container must have p ...