Storing contents of textarea with line breaks - javascript

I'm trying to store the contents of a textarea into localStorage including line breaks.
<textarea cols="40" rows="8" name="delivery-address-input" id="delivery-address-input" required></textarea>
Imagine the contents of the text area are:
1234 Smith Street
Dunedin
New Zealand
$('#delivery-address-input').val() returns the contents including the linebreaks.
But when I try:
localStorage.setItem("contact-address", $('#delivery-address-input').val();
And check the contents:
localStorage.getItem("contact-address")
The linebreaks are all truncated
1234Smith StreetDunedinNew Zealand

Try
var val = $('#delivery-address-input').val().replace(/\n\r?/g, '<br/>');
localStorage.setItem("contact-address", val);
textarea line breaks are like this \n\r and html is <br/> so replace textarea line breaks to html ones .

Related

Append elements to text box in new line using HTML DOM

Suppose i have textbox :-
<input type="text" name="content" id="content"/>
And i am trying append text to this input box in the following manner:-
document.getElementById("content").value+= "A";
The output is something like:-
AAAA....
Each time, the text is getting appended in the same line, how can make the text to append each time to the new line? Like that of below.
A
A
A
.
.
Instead of an input type text, you can use a text area and then style it to look like a text box.
<textarea name="textarea_content" id="tx_content"></textarea>
document.getElementById("tx_content").value+= "A\n";
document.getElementById("tx_content").value+= "A\n";
JSFiddle: https://jsfiddle.net/sx7t3ykc/
The input textbox will support one single line. not multiple lines. that is it's behaviour. That's why your text is shown in a single line.
If you need multiple lines, then you need to use <textarea></textarea> element
input is used for a single line. Try using textarea.
Refer code below:
<textarea type="text" name="content" id="content">
</textarea>
and js will be like this:
document.getElementById("content").value+= "A\n";
I have made you an example that appends a new "A" char every 5 seconds. I use textarea instead of the input tag.
setInterval(appendNewChar, 5000)
function appendNewChar()
{
document.getElementById("myTextArea").value += "A\n";
}
<textarea id="myTextArea"></textarea>
As #GuyFromChennai said, you have to use tag instead of , also, writing '\n' will make the line break, I tried this:
<textarea name="content" id="content"></textarea>
for (let i=0; i<3; i++){
document.getElementById("content").value+= "A\n"";
}

Set text in <textarea>, including newlines

I want to set the text in a <textarea> from a js-function; I'm simply setting the innerText-attribute to a new value. The text is multiline and should be displayed as such. However, newlines are dropped by the browser and the entire text is displayed as one line:
document.getElementById("my_textarea1").innerText = "foo\nbar"; // displayed as "foobar"
document.getElementById("my_textarea2").innerText = "foo\
bar"; // displayed as "foobar"
document.getElementById("my_textarea3").innerText = `foo\
bar`; // again, "foobar"
<textarea id="my_textarea1"></textarea>
<textarea id="my_textarea2"></textarea>
<textarea id="my_textarea3"></textarea>
Is there a way to preserve newlines when setting the text in a <textarea>?
Try it. I use property "value" or "innerHTML" or "textContent":
var area = document.getElementById("my_textarea");
area.value = "foo\nbar";
var area_2 = document.getElementById("my_textarea_2");
area_2.innerHTML = "foo\nbar";
var area_3 = document.getElementById("my_textarea_3");
area_3.textContent = "foo\nbar";
<textarea id="my_textarea"></textarea>
<textarea id="my_textarea_2"></textarea>
<textarea id="my_textarea_3"></textarea>
You can set the value of the textarea, this works with \n, and
`foo\
bar`;
document.querySelector("#my_textarea").value = "foo\nbar"
<textarea id="my_textarea"></textarea>
If that doesn't work for you, use the innerHTML property, the same way:
document.querySelector("#my_textarea").innerHTML = "foo\nbar"
<textarea id="my_textarea"></textarea>
Use area.innerHTML instead, innerText property strips off the new line character
var area = document.getElementById("my_textarea");
area.innerHTML = "foo\nbar";
<textarea id="my_textarea">
</textarea>
You can use \r or \n for this.
Additionally HTML also supports \t to apply tab between two words.
document.querySelector("#my_textarea1").value = "foo\rbar"
document.querySelector("#my_textarea2").value = "foo\nbar"
document.querySelector("#my_textarea3").value = "foo\tbar"
<!DOCTYPE html>
<html>
<body>
<p>New line using "\r" :</p>
<textarea id="my_textarea1"></textarea>
<br>
<p>New line using "\n" :</p>
<textarea id="my_textarea2"></textarea>
<br>
<p>Tab between tow words using "\t" :</p>
<textarea id="my_textarea3"></textarea>
</body>
</html>
According to the HTML Spec:
element . innerText [ = value ]
Returns the element's text content "as rendered".
Can be set, to replace the element's children with the given value, but with line breaks converted to br elements.
Meaning, what you have should have worked. As noted by other answers you could use textContent, value, innerHTML all of which are more likely to work.
If you are set on using textContent, you have a few options/peculiarities, which I'll list out below:
Use an ES6 transpiler such as Babel.js
You can test by enabling ES6 in Stack Overflow's snippet editor.
Refer to (3) options in the snippet below
Note: these seem to work in OSX Safari but not Google Chrome
// Call toString() method
document.getElementById('my_textarea').innerText = "foo\nbar".toString();
// Include the line return character
document.getElementById('my_textarea2').innerText = "foo\r\nbar";
// Apparently, any whitespace or escape character will work
document.getElementById('my_textarea3').innerText = "foo \nbar";
<textarea id="my_textarea"></textarea>
<textarea id="my_textarea2"></textarea>
<textarea id="my_textarea3"></textarea>

how to set angular textarea to only begin with certain words

I have a textarea defined as:
<textarea class="lined" rows="30" name="script_text" ng-model="textContent" placeholder="Enter Script Here" style="width:100%"></textarea>
Is it possible to have each line in the text area only start with a certain list of words?
For example, the user can only enter:
THIS (doesnt matter what comes after)
IS (doesnt matter what comes after)
ALLOWED (doesnt matter what comes after)
But if the user types in:
This is a sentence
next line
and another line
That is not allowed. Is this possible?
Okay. Here a pure Javascript solution. In Angular you can write it with $scope.yourmodel.val() etc.
I tested it with this HTML:
<textarea id="text" class="lined" rows="30" name="script_text" ng-model="textContent" placeholder="Enter Script Here" style="width:100%"></textarea>
I inserted this value:
document.getElementById('text').value
Result:
"Bla das ist ein Text
Nochmal blaa"
First: I got a regex to get each line. You have to go bottom to top. Zero is the last line and one, in my example, the first line:
document.getElementById('text').value.match('(.*)(?=(\n.*){1}$)')
The result:
["Bla das ist ein Text", "Bla das ist ein Text", "
Nochmal blaa"]
Good: Now you can write a for, foreach, whatever loop you want.
You count up and use the cnt in your regex. If you got a null, you're finished.
I got for:
document.getElementById('text').value.match('(.*)(?=(\n.*){2}$)')
a null
Second: You split the each line text by words. The first value is your word:
document.getElementById('text').value.match('(.*)(?=(\n.*){1}$)')[0].split(' ')[0]
Result: "Bla"
If you're using Angular. You could do a great use of the ng-pattern directive.
You could try this:
<textarea class="lined" rows="30" name="script_text" ng-model="textContent" placeholder="Enter Script Here" style="width:100%" ng pattern="/^(THIS|IS|ALLOWED) .*/"></textarea >
Here's a fiddle

<br> is removed when I alert() the content of PRE tag

I want to show the content of this <pre> tag using alert():
<pre> This is the IRNIC Whois server v1.6.2.<br> Available on web at http://whois.nic.ir/<br> Find the terms and conditions of use on http://www.nic.ir/<br> <br> This server uses UTF-8 as the encoding for requests and responses.<br><br> NOTE: This output has been filtered.<br><br> Information related to 'shirzadi.ir'<br><br><br>domain: shirzadi.ir<br>ascii: shirzadi.ir<br>remarks: (Domain Holder) Ehsan Shirzadi<br>remarks: (Domain Holder Address) Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>holder-c: es372-irnic<br>admin-c: es372-irnic<br>tech-c: to52-irnic<br>bill-c: to52-irnic<br>nserver: wres1.irpowerweb.com<br>nserver: wres2.irpowerweb.com<br>last-updated: 2014-01-16<br>expire-date: 2017-10-08<br>source: IRNIC # Filtered<br><br>nic-hdl: es372-irnic<br>person: Ehsan Shirzadi<br>e-mail: ehsan.shirzadi#gmail.com<br>address: Ferdowsi Blv , Mahdi 13 ST, Mashhad, Khorasan razavi, IR<br>phone: +985117688851<br>fax-no: +989155066372<br>source: IRNIC # Filtered<br><br>nic-hdl: to52-irnic<br>org: Fanavarie Etelaate Towseye Saman (Mihannic)<br>e-mail: sales#mihannic.com<br>source: IRNIC # Filtered<br><br></pre>
when I read this content using xx = $('pre').text() and then alert(xx), the is no <br> but when I hard code this content in a variable and alert() I can see them. What is the problem here? finally I want to split the contents by <br>
Try $('pre').html() instead of text(). This should preserve < br > as well as other tags / html entities.
Edit
For completeness, as gillesc said, < br > and other tags will be stripped in alert() (since it does not support inner html). Therefore combination of .html() and replace method is required. Newline can be replaced by \n. Full code would look like this:
xx = $('pre').html().replace(/<br>/g, "\n");
alert(xx);
text() will strip the tags out so use html() instead but alert doesn't support tags so you will need to convert your <br/> before sending it to laert
See this post on how to do just that.
HTML Tags in Javascript Alert() method
Using text() keeps only the inner text, not the HTML markup.
Use html() and eventually replace each captured <br /> by the JS new line character, like said here : How replace HTML <br> with newline character "\n"
Make Like This
<pre id="MyID">This is Test <br /> This is test</pre>
and javascript code
<script>
alert(document.getElementById('MyID').innerHTML);
</script>

Br not working inside P when using Jquery.html()

I am trying to assign to <p> element a large amount of text, which includes some <br /> tags inside, as it's html. I am using the .html() method from JQuery, but it wont show the line breaks.
My code:
var text = "Hello, this is a pretty <br/> large text with some <br/> line breaks inside"
$('.container').append("<p class='myPClass'><p>");
$('.myPClass').html(text);
it does add the text as 'myPClass' html, but it totally ignores the <br/> tags.
the result i am getting is:
<p class='myPClass'>Hello, this is a pretty large text with some line breaks inside</p>
so it would look like:
"Hello, this is a pretty large text with some line breaks inside"
what i want my result to be:
<p class='myPClass'>Hello, this is a pretty <br/> large text with some <br/> line breaks inside</p>
so it would look like:
"Hello, this is a pretty
large text with some
line breaks inside"
what is wrong with my code? or how can i get to do this?
You can also try the following:
var text = "Hello, this is a pretty" + "<br/>" + "large text with some" + "<br/>" + "line breaks inside"
$('.container').append("<p class='myPClass'><p>");
$('.myPClass').html(text);
Try this
var text = "Hello, this is a pretty <br/> large text with some <br/> line breaks inside"
$('.container').append("<p class='myPClass'></p>");
$('.myPClass').html(text);

Categories