How to print each line from textarea using innerHTML and javascript - javascript

For example, if I have the following text inside textarea:
<textarea rows="20" cols="50" id="targetTextArea">
How to
print each
line from
textarea using
innerHTML and
javascript
</textarea>
Then I want to use innerHTML and javascript to parse this textarea and print it on the same page.
Reason, while printing on the page, I would like to prefix by adding some static text to each line, let's say output should look like:
Read How to
Read print each
Read line from
Read textarea using
Read innerHTML and
Read javascript
Thanks in advance.
All of my html page content is below. I want to learn how to print what's in textarea on the same page.
<html>
<body>
Print the contents of textarea as is inside html page
<br/>
<textarea rows="20" cols="50" id="targetTextArea">
How to
print each
line from
textarea using
innerHTML and
javascript
</textarea>
<br/>
<button type="button" onclick="printonpage()">Print on Page</button>
</body>
</html>

You can use the value property to get the text out of the texarea. Then replace each newline with the desired text.
function printonpage() {
var text = document.getElementById('targetTextArea');
var val = text.value;
var arr = val.split("\n");
arr = arr.slice(0, arr.length -1);
var newText = "Read " + arr.join("<br>Read ");
var output = document.getElementById('output');
output.innerHTML = newText;
}
Print the contents of textarea as is inside html page
<br/>
<textarea rows="6" cols="50" id="targetTextArea">
How to
print each
line from
textarea using
innerHTML and
javascript
</textarea>
<br/>
<button type="button" onclick="printonpage()">Print on Page</button>
<div id="output"></div>

You can use following code to do the same. This code using innerHTML and javascript
var textareastext = "<pre>"+ document.getElementById('targetTextArea').value+"</pre>";
document.getElementById('innerhtml').innerHTML = textareastext;
document.getElementById('targetTextArea').style.display = 'none';
window.print();
<textarea rows="20" cols="50" id="targetTextArea">
How to
print each
line from
textarea using
innerHTML and
javascript
</textarea>
<div id="innerhtml"></div>

Check out this fiddle. (I have used jQuery)
Get the innerHTML by the mehod .html().
split it with regex /\n/ (newLine).
Concatenate the substrings with additional "Read".
Alert the final result.
Here is the snippet.
$('#click').click(function() {
var text = $('#targetTextArea').html();
var lines = text.split(/\n/);
var finalText = '';
for (i in lines) {
finalText = finalText + 'Read ' + lines[i] + '\n';
}
alert(finalText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea rows="20" cols="50" id="targetTextArea">How to
print each
line from
textarea using
innerHTML and
javascript</textarea>
<input type="button" value="Click Me" id="click" />

Related

Getting value from dynamic text area

I have a text area field and I want to get value of that text area so I try to get via javascript like:
var body = "Descripción";
var _body = $("div[title='" + body + "']");
Text area
<textarea rows="10" cols="20" id="Descripci_x00f3_n_9b68a148-3221-43c6-abf3-bb32afd3e51b_$TextField" title="Descripción Campo obligatorio" class="ms-long"></textarea>
But I just get object not value.
For some reason when I write in text area this input change with the value I want:
<input id="ClientFormPostBackValue_742e5004-4272-4f68-b3b9-a3c9e3d9ba9b_Descripci_x00f3_n" name="ClientFormPostBackValue_742e5004-4272-4f68-b3b9-a3c9e3d9ba9b_Descripci_x00f3_n" type="hidden" value="this is the value I want">
How can I retrieve value from this input? Regards
var body = "Descripción";
//use `^=` to denote that the attribute should start with a string
var _body = $("textarea[title^='" + body + "']");
console.log(_body.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows="10" cols="20" id="Descripci_x00f3_n_9b68a148-3221-43c6-abf3-bb32afd3e51b_$TextField" title="Descripción Campo obligatorio" class="ms-long">
Stuff
</textarea>
You want to get the data after a button click? if so.
function run() {
var textbox = document.getElementById("Descripci_x00f3_n_9b68a148-3221-43c6-abf3-bb32afd3e51b_$TextField").value;
document.write(textbox);
}
</script>
<textarea rows="10" cols="20" id="Descripci_x00f3_n_9b68a148-3221-43c6-abf3-bb32afd3e51b_$TextField" title="Descripción Campo obligatorio" class="ms-long"></textarea>
<br/>
<button type="button" onclick="run()">get</button>

Split an text into single words, each on a line, with javascript

I wrote this code, with javascript incorporated in html, in order to split the entered text in the input area into single words, each on a line:
function convertToWords() {
var MyVar;
MyVar = document.getElementById("demo");
console.log(MyVar.value.replace(/ /g, "\n"));
var x = document.getElemenyById("myDiv");
x.innerHTML = MyVar.value.replace(/ /g, "\n");
}
<input type="text" value="" id="demo" style="width:100%; height:100px">
</input>
<input type="button" value="Convert to single words" onclick="convertToWords();">
</input>
<br>
<div id="myDiv"></div>
My question, how to let the result be in html for example in a div instead just only as console log?
I tried the highlighted code in the image, but doesnt work :(
Thanks for any help
you can use <br> instead of \n
function convertToWords() {
var MyVar;
MyVar = document.getElementById("demo");
var x = document.getElementById("myDiv");
x.innerHTML = MyVar.value.replace(/ /g, "<br/>");
}
<input type="text" value="" id="demo" style="width:100%; height:100px">
</input>
<input type="button" value="Convert to single words" onclick="convertToWords();">
</input>
<br>
<div id="myDiv"></div>
You have a typo in your function name: getElementById instead of getElemenyById. Also as everybody else suggest, you can use a <br> to put it on a new line.
However look at this solution, it uses more robust coding.
\s as the regex, it splits on all whitespaces. Use this site a nice reference
http://www.regular-expressions.info/tutorial.html and https://regex101.com/ to test your regex.
split, it turns the words into an array. So you can do all kinds tricks with it.
then in the loop, we build block level (div) elements (which are by default placed on a new line) and append them to the result div.
//lets improve this: use eventlisteners instead of inline events
document.querySelector("input[type='button']").addEventListener("click", convertToWords, false);
//using document.querySelector to select the input button based on its node name and type.
// then add a click event to it that refers to convertToWords.
function convertToWords() {
var MyVar;
MyVar = document.getElementById("demo");
var resultDiv = document.getElementById("myDiv"); //try to use descriptive names.
// the use of <br> is not really nice, it works, but this is cleaner
var wordArray = MyVar.value.split(/\s/); //using \s to split on all white spaces
wordArray.forEach(function(element){
//loop over every entry in the array using foreach
var node = document.createElement("div"); //create a block node element;
node.textContent = element; //fill div with the text entry.
resultDiv.appendChild(node); //set node to the result div
});
}
<input type="text" value="" id="demo" style="width:100%; height:100px" />
<input type="button" value="Convert to single words" />
<br>
<div id="myDiv"></div>
Functions used that are interesting to get familiar with:
document.querySelector
Array.prototype.forEach
document.createElement
addEventListener
This should work
x.innerHTML = MyVar.value.replace(/ /g, "<br />");
Use <br> instead of \n to break line in html.
function convertToWords() {
var MyVar = document.getElementById("demo");
//console.log(MyVar.value.replace(/ /g, "\n"));
var x = document.getElementById("myDiv");
x.innerHTML = MyVar.value.replace(/ /g, "<br>");
}
<input type="text" value="" id="demo" style="width:100%; height:100px">
<input type="button" value="Convert to single words" onclick="convertToWords();">
<br >
<div id="myDiv"></div>
Since the browser doesn't care about \n, you can replace the match (a space) with a break.
document.getElementById("input").addEventListener('keyup', function(e) {
document.getElementById("output").innerHTML = e.target.value.replace(/\s/g, "<br/>");
});
<input type="text" id="input">
<div id="output"></div>

Why isn't my javascript function pulling text from text areas?

I would like to take the text from two text areas and insert them concatenated into a following paragraph. I've made a calculator and odd/even validator, and had been able to draw the user input values just fine. Is there something different with text?
<p>
<textarea id="text1" rows="4" cols="50">Type here!</textarea>
<br>
<textarea id="text2" rows="4" cols="50">Now type something here!</textarea>
<br>
<button type="button" onclick="tafunc()">Click here to put text in paragraph below!</button>
</p>
<p id="result"></p>
<script>
function tafunc() {
var first, second, bothtextareas;
first = document.getElementById("text1").value;
second = doucment.getElementById("text2").value;
bothtextareas = first.concat(" ", second);
document.getElementById("result").innerHTML = bothtextareas;
}
</script>
document is misspelled in second assignment. and using value attribute for textarea is correct!
HTML:
<textarea id="text1" rows="4" cols="50">Type here!</textarea>
<br>
<textarea id="text2" rows="4" cols="50">Now type something here!</textarea>
<br>
<button id="btn1" type="button">Click here to put text in paragraph below!</button>
</p>
<p id="result"></p>
change your inline javascript to this:
var btn = document.getElementById("btn1");
btn.onclick = function () {
var first, second, bothtextareas;
first = document.getElementById("text1").value;
second = document.getElementById("text2").value;
bothtextareas = first.concat(" ", second);
document.getElementById("result").innerHTML = bothtextareas;
}
and here's a working jsFiddle

text of input field is not printing while print using window.print()

I have following html layout:
Please fill up this form carefully:
<input type="button" onclick="printDiv('print'); return false;" value="Print" />
<div id="print">
<form action="" method="post">
<input type="text" name="user_name" value="" />
<input type="text" name="address" value="" />
<input type="text" name="date" value="14-06-2015" />
<input type="submit" value="SUBMIT" />
</form>
</div>
and the printDiv('print') function in the head section of that html page:
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
but while printing the form after filled-up, it is not showing the text of input fields that an user entered in the input box. but the predefined text (here the date field) of the input field of the same form is printing as usual.
How can I rewrite the javascript function so that it will print the text of input fields aslo?
That's because innerHTML does not reflect changes by the user in input fields. See innerHTML example: With user input it doesn´t work, why?. A better solution is to use a
CSS stylesheet to control the printable content.
#media print {
body {display:none};
#print {display: block};
}
I am on a phone so I can't test it, you may need to update your HTML and CSS so that you don't have nested conflicting display rules
Some years later, but... i have an idea to solve this that worked for me. It's very simple:
$('form#myId input').bind("change", function() {
var val = $(this).val();
$(this).attr('value',val);
});
We only collect the input value and, in the change event, replace it with the same value that we just entered using attr(). When replacing, it's already recorded in the DOM and will be loaded when we trying to print. I don't think that more explanation is needed, it's very simple.
Regards.
I'm not too sure what you are asking, but the following code will display the user inputs along with the original body if that is all you want. It does not use window.print(); though.
function printDiv() {
var printContents = document.forms[0].elements[0].value + "<br>" + document.forms[0].elements[1].value + "<br>";
var originalContents = document.body.innerHTML;
document.write(printContents + originalContents);
}

document.write(); removes other HTML [duplicate]

This question already has answers here:
Why is document.write considered a "bad practice"?
(17 answers)
Closed 9 years ago.
I'm doing a test for a comment thing. All I want is to have a little text box where you type stuff and a button that says "Add Comment" that will document.write(); what you put in the text box under the add comment thing. But I'm getting a problem where document.write(); seems to be removing all the other HTML that was written out side the javascript (i.e. the textarea and the "Add Comment" button). When I press the "Add Comment" button, what I wrote in the textarea fills up the whole screen and seems to be blotching out the rest. Here is my code:
<html>
<head>
<script language="JavaScript">
function add1(){
var tf = document.getElementById('tf');
add2(tf.value);
}
</script>
</head>
<body>
<p>Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
document.writeln(input);
}
</script>
</body>
</html>
You can not use document.write once the document has completed loading. If you do that then browser will open a new document and it will replace it with the current. So it is the design behavior of document.write
It would be better to use innerHTML to put HTML inside element
Try like this:
<html>
<head>
<script language="JavaScript">
function add1(){
var tf = document.getElementById('tf');
add2(tf.value);
}
</script>
</head>
<body>
<p id="test">Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
var test = document.getElementById('test');
test.innerHTML = input;
}
</script>
</body>
</html>
Also check Why is document.write considered a “bad practice”?
Well instead of using document write, you should append or fill into targeted element, I modified your code a little bit, It might help you.
<html>
<head>
<script language="JavaScript">
function add1(){
var tf = document.getElementById('tf');
add2(tf.value);
}
</script>
</head>
<body>
<p id="test">Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
var test = document.getElementById('test');
test.innerHTML = input;
}
</script>
</body>
</html>
If you wanna append only from original document, you can use it as
test.innerHTML = test.innerHTML + input;
Furthermore
How to append data to div using javascript?
Don't use document.write().Instead use innerHTML
Note:Your code will not work as you are using tf.value where tf is object of textarea which don't have value attribute. So I recommend to use innerHTML.
<html>
<script language="JavaScript">
<head>
function add1(){
var tf = document.getElementById('tf');
add2(tf.innerHTML);
}
</script>
</head>
<body>
<p id="test">Type stuffz here:</p>
<textarea id="tf" wrap="logical" rows="10" cols="50"></textarea>
<!--<input type="textfiel" id="tf" value="Test">-->
<br>
<input type="button" onClick="add1()" value="Add Comment" >
<script type = "text/javascript">
function add2(input){
var test = document.getElementById('test');
test.innerHTML = input;
}
</script>
</body>
</html>
The other comments are correct: document.write() is not something you want to be using. You'll still see that method suggested in some of the older books on JavaScript, but it's really a terrible way to modify the document, for many reasons I won't get into here.
However, no one's suggesting what you can do instead, so I'll point you in the right direction.
If you want to modify elements in your HTML, your best bet is to use the innerHTML property of DOM objects. For example, let's say you have a <div id="output"> that you want to add text to. You would first get a reference to that DOM element thusly:
var outputDiv = document.getElementById( 'output' );
Then you can either completely change the contents of that <div>:
outputDiv.innerHtml = 'Hello world!';
Or you can append to it:
outputDiv.innerHtml = outputDiv.innerHtml + '<br>Hello world!';
Or even more compactly with the += operator (thanks nplungjan):
outputDiv.innerHtml += '<br>Hello world!';
You should also look at jQuery at some point, which gives you a whole boatload of convenience functions to make these kind of manipulations a snap.
I hope this sets you in the right direciton.

Categories

Resources