0

I was wondering if it's possible to print an array into a textarea and after every 4th row (in array or textarea) place a linebreak or something like -----.

In below example I have some input fioelds inside a form which need to be placed in a textarea. Afterwards this textarea is submitted. 'The reason for this is that I use a SaaS platform so I need to work around this problem.

So what I have is this:

  $('.req').on('click', function(){

  var data = [];
  $('.table input').each(function() {
    data.push($(this).val());
  });

  var textarea = document.getElementById("form-message");
  textarea.value = data.join("\n");

  });

As a result I get

21546
Some name
150
12345
Some name
555
54646
Some name
578

How can I print it out like this:

21546
Some name
150
----------------
12345
Some name
555
----------------
54646
Some name
578

Is that even possible?

Thx in advance for any assistence :)

1
  • 2
    Please include the appropriate HTML in your question. Commented Nov 25, 2016 at 16:40

3 Answers 3

1

Here is a quick solution

   $('.req').on('click', function(){

      var data = [];
      $('.table input').each(function(index) {        
        data.push($(this).val());
        if((index+1)%3===0) {
          data.push("-----------------");
        }
      });

      var textarea = document.getElementById("form-message");
      textarea.value = data.join("\n");

    }); 

Using the index value returned by .each() and the modulo in if((index+1)%3 === 0), you can very easily add an additional entry every three lines. Use %n to do it every n lines.

Here is a fiddle showing the solution : https://jsfiddle.net/055074yu/

Sign up to request clarification or add additional context in comments.

Comments

0

Use this fiddle. it may help!

JS:

$('.req').on('click', function(){

  var data = [];
  $('.table.input').each(function(i) {
  if((i+1)%3)
  data.push($(this).val());  
  else
  {
   data.push($(this).val());
   data.push("-------------");
  }
  });

  var textarea = document.getElementById("form-message");
  textarea.value = data.join("\n");

  });

HTML:

<div>
<textarea id="form-message"></textarea>
</div>

<input type="text" class="table input"/>
<input type="text" class="table input"/>
<input type="text" class="table input"/>
<input type="text" class="table input"/>
<input type="text" class="table input"/>
<input type="text" class="table input"/>
<input class="req" type="button" value="button"/>

Comments

0

One possible solution could be:

$('.table input').each(function() {
  data.push($(this).val());
  if ((data.length + 1) % 4 === 0) {
    data.push('----------------');
  }
});

Ok, I've finally made the Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.