Combine the content from multiple text areas and submit it to another text area

****UPDATE****

Thanks to @JasonB, I was able to resolve the previous issue mentioned. Now, I have three additional textareas on the same form that should only appear when their respective checkboxes are clicked. How can I integrate this into my current script? I attempted to group them similarly to TextBoxesGroup but encountered issues with values being submitted even if the checkbox wasn't clicked. Any advice on how to proceed would be greatly appreciated. As a beginner in programming, I am eager to learn and improve.

CODE SNIPPET for the checkboxes:

<textarea id="text" >NAME-
ADDRESS-
ETC-</textarea>
<textarea id="text1">NAME-
ADDRESS-
ETC-</textarea>
<textarea id="text2">NAME-
ADDRESS-
ETC-</textarea> 

<input type="checkbox" id="myCheck"  onclick="myFunction()">DETAILS
<input type="checkbox" id="myCheck1"  onclick="myFunction1()">DETAILS
<input type="checkbox" id="myCheck2"  onclick="myFunction2()">OTHERS

<script>
function myFunction() {
    var checkBox = document.getElementById("myCheck");
    var text = document.getElementById("text");
    if (checkBox.checked == true){
        text.style.display = "block";
    } else {
       text.style.display = "none";
    }
}
function myFunction1() {
    var checkBox1 = document.getElementById("myCheck1");
    var text1 = document.getElementById("text1");
    if (checkBox1.checked == true){
        text1.style.display = "block";
    } else {
       text1.style.display = "none";
    }
}
function myFunction2() {
    var checkBox2 = document.getElementById("myCheck2");
    var text2 = document.getElementById("text2");
    if (checkBox2.checked == true){
        text2.style.display = "block";
    } else {
       text2.style.display = "none";
    }
}
</script>

PREVIOUS QUESTION The challenge I encountered involves a form with multiple textareas. Lacking experience with databases, I opt to store textarea inputs within another textarea upon submission. While I achieved the desired functionality, dynamically added textareas present an issue where only the initial one is captured.

SCRIPT snippet below:

$(document).ready(function () {
    var counter = 1;
    $("#addButton").click(function () {
            if (counter > 15) {
                alert("Only 15 textboxes allowed");
                return false;
            }
        $('<div/>',{'id':'TextBoxDiv' + counter}).html(
              $('<textarea/>',{'id':'myTextArea' + counter ,'class':'myTextArea'}).html( 'STEP ' + counter + ' : ' )
            )
                       .appendTo( '#TextBoxesGroup' )
   $("#myTextArea" + counter).each(function () {
            this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
      }).on('input', function () {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';
      });
                  counter++;

        });

        $("#removeButton").click(function () {
            if (counter == 1) {
                alert("No more textbox to remove");
                return false;
            }
            counter--;
            $("#TextBoxDiv" + counter).remove();
        });
        });

$(document).ready(function() {
  $("#btn-primary").click(function() {
e=1;
    var text55 = $('#textarea55').val();
    var text56 = $('#textarea56').val();
    var text57 = $('#textarea57').val();
    var text58 = $('#textarea58').val();
    var text59 = $('#textarea59').val();
    var text60 = $('#textarea60').val();
    var text61 = $('#textarea61').val();
    var text62 = $('#textarea62').val();
    var myTextArea = $('#myTextArea'+e).val();

  $('#inputTextToSave').val( $('#inputTextToSave').val()+text55+'\n'+text56+'\n'+text57+'\n'+'TROUBLESHOOTING NOTES'+'\n'+myTextArea+'\n'+text58+'\n'+text59+'\n'+text60+'\n'+text61+'\n'+text62+'\n');
e++;
  });

HTML structure used:

<textarea id="textarea55" name="caller"></textarea><br>
<textarea id="textarea56" name="auth"></textarea><br>
<textarea id="textarea57" name="issue"></textarea><br>
<label>TROUBLESHOOTING NOTES:</label><br>
   <body>      
   <div id='TextBoxesGroup'>
   <div id="TextBoxDiv"></div></div>
<input type='button' value='ADD TS STEPS' id='addButton' class="bubbly-button">
<input type='button' value='REMOVE TS' id='removeButton' class="bubbly-button"><br><\body> 
<textarea id="textarea58" name="acct"></textarea><br>
<textarea id="textarea59" name="tid"></textarea><br
<textarea id="textarea60" name="resolution"></textarea><br>
<textarea id="textarea61" name="case"></textarea><br>
<textarea id="textarea62" rows="1" disabled>YANA</textarea>

<input type='button' value='SUBMIT' id='btn-primary' class="bubbly-button"><br>

CSS styling:

div {
  padding: 1px;
  }

textarea {
   outline: none;
  -webkit-border-radius: 8px;
  -moz-border-radius: 8px;
  border-radius: 8px;
      }

.myTextArea {
  width: 535px;
  min-height: 14px;
  overflow-y: hidden;
  font-size: 14px;
  border: 3px solid orange;
  background-color:white;color:mediumvioletred;
  display: block;
  }

body{
  font-size: 14px;
  font-family: 'tempus sans ITC', 'Arial';
  color: mediumvioletred;
  text-align: center;
  background-color: pink;
}

Answer №1

Your textboxes that are generated dynamically can be found within the #TextBoxesGroup element.

If you need to select all of them when submitting, you can simply use $('#TextBoxesGroup textarea'). To combine their contents into a single string with '\n' separators, you can utilize jQuery's .map function to extract the text from each element and place it in an array wrapped in a jQuery object. Then use .get to obtain the underlying array, and finally .join to merge the strings with '\n' as the delimiter.

var contents = $('#TextBoxesGroup textarea')
  .map(function() {
    return $(this).text();
  })
  .get()
  .join('\n');
  
  console.log( contents );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="TextBoxesGroup">
  <div><textarea>One</textarea></div>
  <div><textarea>Two</textarea></div>
  <div><textarea>Three</textarea></div>
</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

Is it necessary to delay until the entire page finishes loading in Selenium 3?

public boolean CheckPageLoadStatus(){ final ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(final WebDriver driver) { return ((JavascriptExecutor) driver).executeScr ...

Stop the form submission from redirecting or refreshing by utilizing JavaScript

I'm facing an issue with a page on my website that includes textboxes generated from php, along with two buttons - GetData and SaveData. My goal is to enable users to press the enter key while editing a textbox and trigger the same action as clicking ...

Executing PHP queries with the help of jQuery

Currently, I am developing a webpage that involves checking a checkbox to trigger a PHP function which queries the table for user existence. If the user exists, a button is displayed allowing them to proceed to the next page. I have made an attempt at thi ...

Using JavaScript to launch a new window with an array of parameters

I am working on an asp.net mvc 3 application that has an Action Method for handling GET requests and returning a page. The code snippet is shown below: [HttpGet] public ActionResult Print(IEnumerable<string> arrayOfIds) { ....................... ...

When using Thunderbird Webextensions, calling .messages.getFull() may result in the Exception 0x80004005 being raised, specifically indicating

This question is a follow-up to a previous question/answer found at: In this scenario, the code attempts to retrieve a list of accounts, select the emailAccountName, get a MessageList object from the specified wantedMailFolderType, and then access a Messa ...

Troubleshooting problems with the height of nested DIV elements

Issue I am attempting to replicate the layout depicted in the image below. The black area represents the body with id="library", the grey div is id="body" (which is not visible due to lack of margins for inner divs), the light blue div is id="sideBar", th ...

When floated to the right, the element is being pushed onto the next line in Firefox

Within a div, there are four elements. I specifically want the last element to be positioned on the far right, so I applied float: right to it. However, in Firefox, the last element gets pushed to the end of the next line instead. This issue does not occ ...

Issue with function execution in MVC after invoking from jstree

My jquery code is supposed to trigger the MVC function call: $(document).ready(function () { alert("ddddd"); $("#divJsTreeDemo").jstree({ "plugins": ["json_data"], "json_data": { "ajax": { "type": "POST", "url": "/W ...

What is the best method for developing a draggable element that remains stable?

I have developed a simple script for draggable elements, however, I am facing an issue. Whenever I move the mouse quickly, the element loses focus. Is there a way to improve the stability of the dragging functionality regardless of how fast I move the mou ...

The performance of three.js PointsMaterial is sluggish when utilizing large sprites or shapes, causing a decrease in overall

Currently, I am handling a point cloud with approximately 60,000 vertices. Interestingly, when I view the cloud at a smaller scale, performance remains acceptable. However, as soon as I zoom in and larger sprites/plans/points become visible on the screen, ...

Transform the componentDidUpdate method that uses prevProps into a custom hook integrated with Redux

Trying to convert a life cycle method into a hook is not working as expected. When the component mounted, if the user ID exists in local storage, the user is connected and their name is displayed in the navbar. If they disconnect and reconnect, their name ...

Incorporate a linked select dropdown into the registration form

I am working on a sign-up form and trying to integrate 2 linked select boxes into the form. The code for the linked select boxes works fine separately but when I attempt to add it to the form, it doesn't display as expected. I attempted to incorporate ...

What might be the reason my $q.defer().resolve is not functioning properly?

I have noticed an interesting behavior in my code. When I define a promise in the service and return it back (promise1 in this case), it does not resolve at all. However, when I define the promise in the controller (promise2), it works perfectly fine. Why ...

Execute the function when the control becomes visible

Currently, I possess an input control: <input id="someID" class="form-control" type="text" name="SomeData" data-ng-model="vm.SomeData"> I have a requirement to set the initial value of vm.SomeData upon user scrolling down to this control. As a begi ...

What is the best way to locate an element in the HTML content that contains the class 'sponsored-post'?

This code snippet is flawed as it assigns 'none' to the variable article, even though the variable articles contains all the listing results. articles = soup.select('.listingResult') for article in articles: # <div class=&qu ...

Tips for testing parallel, mocked data requests in JEST by simulating cached responses with a 500ms limit

In order to simulate parallel requests fetching data from different sources, I have implemented tests that introduce artificial latency for each request. The goal is to return a simple string with an identifying digit to determine whether the data has been ...

What is the proper method to set up jQuery in scripts loaded via AJAX? I keep receiving the error message: 'Uncaught TypeError: Object #<Object> has no method'

I have developed a website with an index page that contains a div for loading the content of each individual page. Initially, I included external JS files and performed initializations within each separate page. However, most of the time when the page loa ...

Python Selenium: How to locate elements using xpath in the presence of duplicate elements within the HTML code

Currently, I am utilizing selenium to extract data from a liquor sales website to streamline the process of adding product information to a spreadsheet. My workflow involves logging into the website using selenium and searching for the specific product. Wh ...

The sign out option fails to erase the data stored in Local Storage

After implementing a login feature that stores a token in local storage, I encountered an issue with the logout button. The intention was for the button to delete the token from local storage and set the user to null upon clicking it. However, this functio ...

Extracting values from URL query parameters in Vue.js

When dealing with Vue.js callback URLs, I encounter situations where I need to extract a parameter value from the URL. For instance, consider this return URL: http://localhost:8080/#/sucesspage?encryteddata=abdeshfkkilkalidfel&9a I attempted to retrie ...