Textarea to variable: Spacing - javascript

I'm taking the content of a textarea and saving it in a variable. But I notice that when I save the content, the variable ignores the spacing (new lines). How do I fix this. I want the variable to store the structure of the text, with all the new lines and tabs. My code in which I save the content from the textarea is below:
let content = document.getElementById('content').value
The whole function is below:
function mail(){
var options = document.getElementById('users').options
let content = document.getElementById('content').value
var emails = []
var regex = /\*user\*/gi
for(var i = 2; i < options.length; i++){
emails.push(options[i].innerHTML)
content = content.replace(regex, emails[i-2])
window.open(`mailto:${emails[i-2]}?subject=To ${emails[i-2]}&body=${content}`)
}
}
Thanks!!! Any help is appreciated!

Actually, spaces and new lines are exists but because you put your content in html (body{}), they are invisible.
some solutions:
let content = document.getElementById('content').value.replace(/\n/g,"<br/>").replace(/ ( +)/g,function(a,b){var s="", i=0; for(;i<b.length;i++)s+=" "; return " "+s;});
or this:
let content = "<pre>"+document.getElementById('content').value+"</pre>"
or this:
let content = "<div style='white-space: pre'>"+document.getElementById('content').value+"</div>"
The above solutions were for when the body is html.
Edit:
I guess this will solve your problem:
let content = escape(document.getElementById('content').value);

The variable does contain new lines if new lines are entered in the textarea. Keep in mind that textarea will wrap the text to fit it so if you see wrapped text, that doesn't mean there is a new line character in the text.
<textarea id="content"></textarea>
<input type="button" value="submit" onclick="msg()">
<script>
function msg() {
let message = document.getElementById('content').value;
alert(message);
}
</script>

Related

Losing CSS styling upon printing

I am using a style sheet to properly print out a webpage. The webpage has fields sat next to each other but upon printing these fields no longer sit next to each other but instead cascade down the sheet. I have created a style sheet but I'm not sure exactly how that is supposed to stop this from happening unless I hard code into the style sheet what I want to happen. Unfortunately I can't do that because I need to print out several different pages that have different layouts.
Is there any way to fix this?
function removeLinks(printDiv) {
var all_links = document.getElementById(printDiv).getElementsByTagName("a");
for (var i = 0; i < all_links.length; i++) {
all_links[i].removeAttribute("href");
}
}
function printdiv(printDiv) {
var divCaseNote = document.getElementById(printDiv);
var oldstr = document.body.innerHTML;
var oldTitle = document.title;
if (divCaseNote != null) {
divCaseNote.style = "padding: 20px;";
innerHTML = divCaseNote.innerHTML;
}
removeLinks(printDiv);
var headstr = "<html><head rel=\"stylesheet\" media=\"all\" link href=\"/CSS/style.css\"/><title> </title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printDiv).innerHTML;
document.body.innerHTML = headstr + newstr + footstr;
document.title = oldTitle.replace(" - View Case Note", "");
window.print()
document.body.innerHTML = oldstr;
document.title = oldTitle;
EDIT: A snippet of the html output of this function. It holds all the correct divs for the columns but instead of printing the columns side by side they print cascading down the page.
<div class=\"view-value\" style=\"border-left: none;\">
Jerry</div></div></div>
<div class=\"col-md-3\"><div class=\"media-body\">
<div class=\"view-label\">Participant's Last Name</div>
<div class=\"view-value\" style=\"border-left: none;\">Field</div>
What it should look like
[
What it actually looks like after printing
The problem is that the inline styles are getting obliterated by this statement:
divCaseNote.style = "padding: 20px;";
which removes all the style attribute and replaces it with just the padding.
To add/alter the padding but nothing else you want to change just that property so try:
divCaseNote.style.padding = "20px";

Replacing text with new text when button click

I have 3 data in the JSON file and want each data to be displayed 1 by 1 at a single click.The problem is the previous data was'nt replaced by the new data as the button was click. They ended up being side by side (image below). How do i overcome this? Thanks in advance.
JSON FILE
[
{"quote": "Everyday Is A New Day"},
{"quote": "Trust Your Guts"},
{"quote": "All The Best"}
]
HTML
<p id="text"></p>
<button id="btn">GENERATE</button>
JAVASCRIPT
var text = document.getElementById("text");
var btn = document.getElementById("btn");
var i=0;
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'data2.json');
ourRequest.onload = renderHTML;
ourRequest.send();
});
function renderHTML(data) {
var htmlString =data[i].quote;
i++;
text.insertAdjacentHTML('beforeend', htmlString);
};
instead of
text.insertAdjacentHTML('beforeend', htmlString);
just use
text.innerHTML = htmlString;
insertAdjacentHTML doesn't replace the html.
Instead of using insertAdjacentHTML, set innerHTML directly. So your new function would look like:
function renderHTML(data) {
var htmlString =data[i].quote;
i++;
i %= data.length; // new
text.innerHTML = htmlString; // changed
}
I also inserted the line i %= data.length; so you don't go off the end of the array, and instead loop around to the beginning of data.

Eloquent JS Exercise (Ch.18 Q. 2)

I was hoping someone can help me figure out what I'm doing wrong... There's this exercise in the Eloquent JS book that asks you to write some code that can suggest words/values to users as they type... The code I've written is below. What happens is that when I run the code, the div element's text content changes to the wrong value. Specifically, it's set to a string of all the elements inside the array 'terms'. I really cant figure out why this happens!
<input type="text" id="field">
<div id="suggestions" style="cursor: pointer"></div>
<script>
// Builds up an array with global variable names, like
// 'alert', 'document', and 'scrollTo'
var terms = [];
for (var name in window)
terms.push(name);
var input = document.querySelector('input');
var div = document.querySelector('#suggestions');
input.addEventListener("input", function(event){
var last = input.value.lastIndexOf(" ")+1;
var check = input.value.slice(last);
var reg = new RegExp(check);
for (var i=0; i<terms.length; i++) {
if (reg.test(terms[i])) {
var text = document.createTextNode(terms[i]);
div.appendChild(text)};
};
})
</script>
I guess you forgot to clean the div before each change in the input.
I also added a space after each word to make the output more readable.
// Builds up an array with global variable names, like
// 'alert', 'document', and 'scrollTo'
var terms = [];
for (var name in window)
terms.push(name);
var input = document.querySelector('input');
var div = document.querySelector('#suggestions');
input.addEventListener("input", function(event){
div.innerHTML = '';
var last = input.value.lastIndexOf(" ")+1;
var check = input.value.slice(last);
var reg = new RegExp(check);
for (var i=0; i<terms.length; i++) {
if (reg.test(terms[i])) {
var text = document.createTextNode(terms[i] + ' ');
div.appendChild(text)};
};
})
<input type="text" id="field">
<div id="suggestions" style="cursor: pointer"></div>
With this code, you will display the name of the properties from the window object that contains the last word from the input. Try it writting "window location document". Is it what you are looking for?

Putting HTML tags through js

I need to simply display some errors from my node server to the user, this is my code:
if(text.length > 1){
text = text.join("<br>");
console.log("array:",text);
}else{
text = text[0];
}
and then I do:
myNewDiv.innerHTML = text;
and append it to the page, the problem is, that js converts the <br> into <br>, so the next errors are not displayed on new line, but like this:
some text br other text
Maybe you can send the HTML string in a different format from node, but this will work either way in your clientside code:
If you are using Jquery you can use:
function DecodeHtmlString(htmlString){
return $('<div/>').html(htmlString).text();
}
Vanilla JS:
function DecodeHtmlString(htmlString){
var temp = document.createElement("textarea");
temp.innerHTML = htmlString;
return temp.value;
}
It's not clear from the code you provided exactly what you are doing wrong, but here is a working version of what you are trying to do:
http://jsfiddle.net/03z6k7ko/
var text = ['Hello', 'world!'];
if(text.length > 1){
text = text.join("<br/>");
}else{
text = text[0];
}
document.getElementById('message').innerHTML = text;

Modify variable from input and place in new div based on input variable

This is related to my last questions, but that already had alot of answers so I did not want to modify it with more stuff to avoid confusion.
I can take the input from the input text with the id 'test', and I can display it on the div labeled 'result', but I am not able to modify the output to div
function createLinks()
{
var input = document.getElementById('test')
if(str.indexOf("VALUE")>=0){
var lin = "something";
}
else {
var lin = "somethingelse";
}
var div = document.getElementById('result');
div.innerHTML = lin.value;
}
The HTML is working currently as follows:
<input type="text" id="test" size="16" title="Coming Soon" onkeypress="createLinks()"/>
<input type="submit" style="margin-left: 10px;" value="Search" class="button1"/>
<div id="result"></div>
I work with mainly CGI and have very limited knowledge of JS so I am probably missing something simple or this plain wont work. Thanks for the help in advance.
I fixed your code to what I think you wanted:
function createLinks()
{
var lin;
var input = document.getElementById('test');
if(input.value.indexOf("VALUE")>=0){
lin = "something";
}
else {
lin = "somethingelse";
}
var div = document.getElementById('result');
div.innerHTML = lin;
}
What was wrong was that:
[1] str was not defined
[2] lin was not globally defined, so you couldn't access it.
I updated the code so that it will make result say something if the textbox has VALUE typed in it and somethingelse if it doesn't, and that you can also press the Search button instead of pressing a key.
Try This: str not defined and lin is the value.
function createLinks()
{
var input = document.getElementById('test')
if(input.value.indexOf("VALUE")>=0){
var lin = "something";
}
else {
var lin = "somethingelse";
}
var div = document.getElementById('result');
div.innerHTML = lin;
}

Categories

Resources