0

I'd like to make a custom order form for my website which will allow customers to input a custom engraved message into a textarea. Customers can engrave a maximum of 3 lines.

I'd like to collect the text from the textarea, and separate each line into its own variable. For example, if the customer typed into the textarea:

Amy and John Smith
12/14/95
I'll always be by your side

Is it possible to store each line as its own variable? (In JavaScript)

var engravementLine1 = "Amy and John Smith";
var engravementLine2 = "12/14/95";
var engravementLine3 = "I/'ll always be by your side";
  • Yes, it is possible. For example, you can use `Scanner` class with its `nextLine()` method. – PM 77-1 Mar 02 '20 at 23:48
  • 2
    Does this answer your question? [parse a textarea in substrings based on line breaks in Javascript](https://stackoverflow.com/questions/3800795/parse-a-textarea-in-substrings-based-on-line-breaks-in-javascript) – Heretic Monkey Mar 02 '20 at 23:51
  • Then you can use [Unpacking array into separate variables in JavaScript](https://stackoverflow.com/q/3422458/215552) – Heretic Monkey Mar 02 '20 at 23:53
  • 1
    You can do this easily with RegExp, but I would actually use three different ``s instead, so you can do individual test on each line and produce a separate error corresponding to other failures you should also program in. Like how long can each line be? What can the text on the specific line contain? Make sure you do checks Server-side also, as that is really the end-all be-all to your site integrity. – StackSlave Mar 02 '20 at 23:54

2 Answers2

0

If you're looking to keep a specific format I wouldn't recommend using textarea as users are known to input unpredictable things.

You can get each line of a <textarea id="mytextarea"></textarea> by using this code:

document.getElementById('mytextarea').value.split('\n');

This will give you something like this

 const resultArr = ["Amy and John Smith", "12/14/95", "I'll always be by your side"]

You can then use resultArr and map everything to your variables like so

var engravementLine1 = resultArr[0];
var engravementLine2 = resultArr[1];
var engravementLine3 = resultArr[2];

Update: Look at parse a textarea in substrings based on line breaks in Javascript

haron68
  • 741
  • 1
  • 5
  • 19
0

You can split the value of the input using .split(/\n/), where /\n/ is a regular expression for a line break. So doing this:

const string = "
Amy and John Smith
12/14/95
I'll always be by your side
"

const splitUp = string.split(/\n/)

Will give you an array where each line is a new item in an array, which can then easily be assigned values.

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78