JavaScript: Retrieve values from individual textareas with identical class names

Imagine you have multiple text areas like the ones below:

<textarea class='save'></textarea>
<textarea class='save'></textarea>
<textarea class='save'></textarea>

All of them are assigned the class 'save'. The goal is to use jQuery/JavaScript to extract the text from each textarea with the 'save' class.

Here's what I've come up with so far:

$('#getText').click(function(){
    var text = $('.save').text(); 
});

With this code, all the text values are retrieved and stored in the variable. However, I'd prefer to loop through each textarea first for potential editing. Here's my conceptual plan:

On button click -> Retrieve first '.save', encapsulate it within <p></p>, include a 
<h1>Title</h1>, and store this in a variable/array.

The output format would be as follows:

<h1>Text 1</h1>
<p>text from textarea 1</p>

<h1>Text 2</h1>
<p>text from textarea 2</p>

<h1>Text 3</h1>
<p>text from textarea 3</p>

This process should be repeated for each '.save'. Any suggestions on how to achieve this?

Answer №1

If you utilize jQuery's each() function, you can loop through each element selected using $(".save").

After that, you have the flexibility to perform any actions needed. In the example provided below, an array is created with titles and during each iteration of the each() function, a new title is retrieved, added to the html string, and combined with the value from the current textarea, all enclosed in a <p> tag.

let titles = ["text 1", "text 2", "text 3"]
const result = $("#result")

$('#getText').click(function(){
    let html = ""
    var textAreas = $('.save')
    textAreas.each(function(idx) {    
      let txtAreaValue = this.value;
      let title = titles[idx];
      html += "<h2>" + title + "</h2>" 
      html += "<p>" + txtAreaValue + "</p>";
    })
    console.log(html);
    result.html(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class='save'></textarea>
<textarea class='save'></textarea>
<textarea class='save'></textarea>
<input type="button" value="get" id="getText"/>
<div id="result"></div>

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

Using ThreeJS to assign various textures based on the position of the object

Recently, I delved into the world of ThreeJS and embarked on creating a model of the Earth using a Sphere mesh. Alongside this, I crafted a model of the Sun and now desire to infuse two distinct textures onto the Earth model based on its orientation. Speci ...

Adjust the color of the background when hovering with the cursor

I am currently working on a project with a menu of buttons that dynamically changes based on the elements in a list. For instance, if my list contains ["A", "B", "C"], then I would have a menu with 3 buttons. Here is how I display the buttons using a java ...

Testing components in Angular using Renderer2

Recently, I came across an Angular component with the following structure: constructor( @Inject(INJECTION_TOKEN_WINDOW) private window: Window, private renderer: Renderer2 ){} ngOnInit() { this.renderer.addClass(this.window.document.body ...

I am experiencing an issue where the onChange event is not being triggered in my React application

I am currently in the process of creating a random football team picker and handling the database on my own. However, I seem to be encountering issues with the inputs. import React, { use, useRef, useState } from "react"; const fetchAll = async ...

What could be causing a Bootstrap JavaScript error to appear within my Chrome Extension?

I am currently working on developing a Chrome extension that will display a button on Google's search results page, and when the user hovers over the button, a modal window will appear. While I have been able to make the modal window partially appear ...

Create a collection of data by retrieving values from a web service response

My goal is to populate table values from a webservice response. The issue arises when the response format is not compatible with the table. The response structure may vary. 0:{name: "image.png", base64: "iVBORw"} 1:{name: "download.png", base64: "iVBO"} 2 ...

Swap out the HTML tags for some Angular 6 text!

I have a specific word in my code that I want to change using an HTML tag and apply the style with the themecolor class. <h2 class="mb-30" [innerHTML]="main_title"></h2> Here is a preview of the result: This is some sample text. I need to ...

Can I send both a list of files and an entire JSON object in a FormData object to an ASP.NET CORE MVC Controller?

I'm looking for a way to send a formdata object to an MVC controller that includes both a JSON object with nested objects and a list of files. I've attempted to stringify the object into a JSON object, but the controller is unable to read the pro ...

Is it possible to operate a jQuery mobile web application while disconnected?

Recently, I've been experimenting with the idea of creating a web application using jQuery Mobile that involves utilizing forms such as checkboxes, text fields, and combo boxes. The tasks associated with this app are quite simple, but they require dat ...

Setting up node.js for angular - serving static files with connect.static and running unit tests

Currently, I am in the process of setting up a basic node webserver by following a tutorial outlined in Pro AngularJS published by Apress. Node.js along with both the connect and karma modules have been successfully installed on my system. During the ins ...

Ways to break apart a string of text without a regular pattern

Here is the data I am working with: Huawei Y7P Art-L28 (4/64gb) (AAAAAAAAAAAAAA) EXP:02/19/2020 Huawei Y9 prime 2019 (BBBBBBBBBBBBBBB) EXP:07/17/2019 Oppo A31 4gb/128gb (CCCCCCCCCCCCCCC) Vivo Y15 5000mah 4GB/64GB (1901) (DDDDDDDDDDDDDDD) EXP:06/14/2019 I ...

Failure of Styling Inheritance in Angular 2 Child Components from Parent Components

My Parent Component utilizes a Child Component. I have defined the necessary styles in the Parent CSS file, and these styles change appropriately when hovering over the div. However, the Child Component does not inherit the styling classes of the Parent Co ...

How do I submit an array of objects in Laravel?

I am currently working with a dynamic table that allows users to add and delete rows. Each row contains input fields where users can enter data for an object. At the moment, I am manually assigning index numbers to the name attribute like this: <input ...

Tips for positioning a solitary md-tab component to the right

Can a single md-tab element be aligned to the right of md-tabs while keeping the rest of the tabs in their original position? ------------------------------------------------------------------------- | Tab 1 | Tab 2 | Tab 3 | ...

I'm having trouble getting the code to work properly after the "else" statement using both jQuery and Javascript. My head is

Being a newcomer to javascript and jquery, debugging and viewing log files seem like a challenge compared to php. Any help from experienced individuals would be greatly appreciated. Although my code mostly works fine, I'm having trouble with the if/e ...

Is there a way to automatically play videos without any audio?

Is there a way for my video to automatically start playing when the page loads, without sound? I want it to function similar to the video on this webpage: . I've experimented with various jQuery, JavaScript, and CSS techniques from online resources, ...

AngularJS - Determine the correct condition or make a choice from the available options

I'm having trouble figuring out how to save the option I select to a viewmodel. The ng-model should save whatever option I choose, and if nothing is selected, the value should default to "Select One." The available options are YES (true) / NO (false). ...

A guide to efficiently reusing parameter definitions in functions using JSDoc

Currently, I have HTTP handlers set up in my express application. I want to use JSDoc annotations to document these handlers in a reusable manner. Here is what I currently have: /** * * @param {functions.Request} req * @param {functions.Response} res ...

Using jQuery to toggle the visibility of content with a single button

After using a third-party tool to modify my html content, I am facing an issue. The html now includes both the changed/deleted text as well as the new additions. For instance, the html code looks like this: https://i.sstatic.net/nuseQ.png My goal is to ...

After changing the form action using jQuery, the GET variables mysteriously vanish

I am attempting to modify the action URL of a form using jQuery. Below is the code I have implemented: <form id='form_a' action='browse.php' method='get'> <input type="submit" value="Filter" id='but_a'& ...