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>
Related
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"";
}
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 .
Imagine the following scenario: I have this HTML body (this is just one example, the delimiters will be configurable by 3rd parties, so no way to use DOM methods like getElementBy...) :
<div id="login">
<form method="post" action="https://site.com/login.html?skin=webmail" id="fWM">
<fieldset>
<p><label>Login<br><input type="text" class="inpText" name="user" id="user"/> </label><span class="provider">#isp.com</span></p>
<p><label>Password<br><input type="password" class="inpText inpPass" name="pass" id="pass"/></label></p>
</fieldset>
<p id="forgot">
Forgot password? <span class="pipe">|</span>
Help
</p>
<br><a><input type="submit" value="" id="bOK"/></a></p>
</form>
Ok, this is just a part of some html body asking for Login and Password. As you can see, I have
< fieldset > and < /fieldset > and for this example those are my delimiters. This mean, everything between this delimiters I want to change for another html code. I have some 'begin of code' like this to you have some idea about what I'm talking:
var myBody = document.body.innerHTML;
var beginInject = myBody.indexOf("<fieldset>");
var endInject = myBody.indexOf("</fieldset>");
var InjectBody = 'Hello World!';
//what to do now to put Hello World! between the <fieldset> and </fieldset>??
Remember this is just one example, I can need to put the delimiters like < body> and < /body> or something like: "Click Here to Start download" and "Thank you for visiting this website"... What I mean is: can be anything inside the body, and between the 2 delimiters I want to put my HTML code. Thank you.
If you insist to make it your way, use
var beginText = "<p>",
endText = "</p>",
injectText = 'Hello World!';
var html = document.body.innerHTML,
beginPos = html.indexOf(beginText),
endPos = html.indexOf(endText);
document.body.innerHTML =
html.substring(0, beginPos + beginText.length)
+injectText
+html.substring(endPos + endText.length);
Demo
But be aware that this way
You will remove all event listeners inside your body
You will lose all element's properties (not attributes)
Browser will reload all body (slow)
And it won't work on all cases. For example:
If you search for <p>, you won't match <p class="myClass">
If you search for <p a="b" c="d">, you won't match <p c="d" a="b">
Text could be matched instead of real elements, for example if text appears in a textarea.
endPos could be smaller than beginPos, for example because it appears in a textarea.
The problem is that You can't parse [X]HTML with regex because Zalgo is coming, so it's even worse to parse it with just text.
You could use document.querySelector.
For example:
document.querySelector('#login fieldset');
And its argument can be the selector that you want. This way you don't have to worry if you are matching by id, by class, by tagname, by name, etc.
How do I change the case of a character in a textbox/textarea to lowercase onchange?
<html>
<head>
<title>Page Title</title>
<script>
function f2(string)
{
string=string.toUpperCase();
alert(string);
}
</script>
</head>
<body>
<p>Here are my text entry objects:</p>
<form>
<p>
Change the scripting (still using one function) so that the text from the alert is shown in uppercase from the textbox but lowercase from the textarea:<br>
<textarea onchange='f2(this.value);'></textarea>
</p>
</form>
</body>
Have you tried;
function f2(textarea)
{
string = textarea.value;
alert(string);
string = string.toLowerCase();
textarea.value = string;
}
With the modification to the onChange as;
<textarea onchange='f2(this);'></textarea>
Simply change the value and assign it back.
<textarea onchange='this.value=this.value.toLowerCase();'></textarea>
Because nobody fixed your code
HTML:
<p>Here are my text entry objects:</p>
<form>
<p>
Change the scripting (still using one function) so that the text from the alert is shown in uppercase from the textbox but lowercase from the textarea:<br>
<textarea></textarea>
</p>
JS:
document.getElementsByTagName("textarea")[0].addEventListener("change", function () {
this.value = this.value.toLowerCase();
});
You want to add a change event handler. Inside the event handler you merely overwrite the value property of the element with the string changed to lowerCase.
I also fixed your in-line javascript in your HTML. It is the devil, avoid it.
Live Example
Just use the .toLowerCase() method.
Use onchange='this.value = this.value.toUpperCase();' to make the text uppercase. Replace toUpperCase with toLowerCase for the opposite.
If desired, you can use your own function instead of just toUpperCase, passing either just the textarea's value or the entire textarea. For example (value only):
<!-- HTML -->
<textarea onchange='this.value = f2(this.value);'></textarea>
// JavaScript
function f2(oldText) {
var newText = oldText.toUpperCase();
return newText;
}
Or (entire textarea):
<!-- HTML -->
<textarea onchange='f3(this);'></textarea>
// JavaScript
function f3(ta) {
ta.value = ta.value.toUpperCase();
}
I would pass this and then work on it like a DOMNode:
<p>Here are my text entry objects:</p>
<form>
<p>
Change the scripting (still using one function) so that the text from the alert is shown in uppercase from the textbox but lowercase from the textarea:<br>
<textarea onchange='f2(this);'></textarea>
</p>
</form>
function f2(el) {
el.value = el.value.toLowerCase();
}
http://jsfiddle.net/HDR8t/1
Problem 1
I believe the onchange event only gets fired when the <textarea> no longer has focus. Instead, you'll want to use the onkeyup event.
Problem 2
You're only passing the string to the function. If you want to change the actual text in the <textarea>, you'll need to pass the actual DOM element to your function:
<textarea onkeyup="f3(this)"></textarea>
Problem 3
Once you pass the element into your function, you'll need to update its value attribute:
function f3(elem) {
elem.value = elem.value.toLowerCase();
}
Try the [.toLowerCase()][1] method.
<textarea onchange='this.value=this.value.toLowerCase();'></textarea>
<html>
<body>
<script language="javascript">
function getSelectionHTML()
{
var div = document.getElementById("myDiv");
if (document.createRange) {
var textNode=div.firstChild;
var rangeObj=document.createRange();
rangeObj.setStart(textNode,0);
rangeObj.setEnd(textNode,5);
div .innerHTML = div .innerHTML.replace(rangeObj.toString(), '<span style="background-color: lime">'+rangeObj.toString()+'</span>')
}
}
</script>
<div id="myDiv">
asdf as<b>dfas df asf asdf sdfjk dvh a sjkh jhcdjkv</b> iof scjahjkv ahsjv hdjk biud fcsvjksdhf k
</div>
<form name="aform">
<input type="button" value="Get selection" onclick="getSelectionHTML()">
</body>
</html>
Ok. Let me explain -> getSelectionHTML() method is for selection of characters from 0 to 10. I am getting the values by "myDiv" id. but inner bold, italic & other tags are giving me trouble.
In simple words, I just want to make selection of first ten characters (& apply them span tag) which are in "myDiv" tag.
What exactly I am missing?
This is much easier in IE using TextRange, which is based around characters, words and sentences rather than nodes and offsets. In non-IE browsers, you'll need to do tedious manual traversal of text nodes in the DOM. However, even if you were to do this to get the first ten text characters within your <div> (which would be "asdf asdfa"), your strategy is flawed because you're using a replacement on innerHTML, which would try and fail to find "asdf asdfa" (innerHTML would start with "asdf as<b>dfa", or possibly "asdf as<B>", depending on browser).
What I would suggest is doing the DOM traversal to find all text nodes within the <div> and surrounding the parts of the text nodes you need with <span>s, thus avoiding Ranges altogether and therefore making this work in all major browsers.
You're trying to select e.g. character 1 to 10 of your text. But when using Range.setStart and .endStart, the first parameter is the text node containing your text. If you browse through the DOM with Firebug (or Web Inspector), you'll notice that character 10 of your text resides in another element (the <b> element), with its own text node.
BTW, you left out several required elements/tags, which can also be a source of errors.
My corrected version reads
<!DOCTYPE html>
<html>
<head>
<title>Title element is required</title>
<body>
<script>
function getSelectionHTML()
{
var div = document.getElementById("myDiv");
var bEl = document.getElementById("bEl");
if (document.createRange) {.
var textNode=div.firstChild;
var rangeObj=document.createRange();
rangeObj.setStart(textNode,0);
rangeObj.setEnd(bEl.firstChild,2);
alert(rangeObj.toString());
// div.innerHTML = div.innerHTML.replace(rangeObj.toString(), '<span style="background-color: lime">'+rangeObj.toString()+'</span>');
}
}
</script>
<div id="myDiv">
asdf as<b id="bEl">dfas df asf asdf sdfjk dvh a sjkh jhcdjkv</b> iof scjahjkv ahsjv hdjk biud fcsvjksdhf k
</div>
<form name="aform">
<input type="button" value="Get selection" onclick="getSelectionHTML()">
</form>
</body>
</html>
Now rangeObj contains the selected text, but you can't simply insert a <span> element the way you tried, because elements can't be nested this way:
<span>asdf as<b>dfa</span>s df asf…