Adding newline in HTML using Javascript - javascript

I'm trying add a newline after some text every time a button is pressed. Here is the part of HTML file concerning the question -
<input type="text" id="fname" name="fname">
<button type = "button" onclick = "prtText('fname')">SEND</button>
<p id="para"></p>
<script>
var node = document.createElement("P");
function prtText(addr)
{
var x = document.getElementById(addr).value;
var txt = x + '\n'
var textnode = document.createTextNode(txt);
node.appendChild(textnode);
document.getElementById("para").appendChild(node);
}
</script>
Now, when I run the HTML file, every time I press the button, the text on the input box should get printed with a newline. Like this-
ExampleText
ExampleText
But it gets printed something like this-
ExampleText ExampleText.
I have tried the other method like this - var txt = x + '<br/>', but it prints like this - ExampleText<br/>ExampleText<br/> and doesn't print a line break.
What do I do?

It's generally not a good idea to use inline event handlers. Here's a snippet that adds the input value to paragraph (p#para) and empties the input element on clicking button#sendBttn. The value is wrapped in a div, a block level element, meaning it will always start on a new 'line'. 1
1 You can also end a value string with <br>, but in that case you can not use a innerText, createTextNode or textContent.
document.addEventListener("click", printValue);
function printValue(evt) {
// only do stuff when the button was clicked
if (evt.target.id === "sendBttn") {
const inputEl = document.querySelector("input#fname");
const value = inputEl.value.trim();
// value may be empty
if (value) {
// create an block element
const newLine = document.createElement("div");
// fill with the value
newLine.textContent = "Sent: " + value;
// append it to the existing paragraph
document.querySelector("#para").appendChild(newLine);
// reset input value
inputEl.value = "";
// focus back to the input field
inputEl.focus();
}
}
}
body {
font: normal 12px/15px verdana, arial;
margin: 2rem;
}
#para div {
padding: 2px 3px;
border: 1px solid #eee;
max-width: 500px;
margin: 2px;
}
<input type="text" id="fname" name="fname">
<button type="button" id="sendBttn">SEND</button>
<p id="para"></p>

<input type="text" id="fname" name="fname">
<button type = "button" onclick = "prtText('fname')">SEND</button>
<p id="para"></p>
<script>
var node = document.createElement("P");
function prtText(addr)
{
var txt = '\n'+ document.getElementById(addr).value ;
document.getElementById("para").innerText+= txt;
}
</script>
Here you go. HTML elements have property innerText which allows you to edit contents of element. Beware that it will change inside elements if there are any.

That happens because new lines are transformed into spaces in HTML. For example:
<p>
This is a sentence. Sometimes sentences get too big to
fit inside a single line, so we break the line in two.
</p>
In the above example, the text node inside the <p> element, has a newline, but the rendered output doesn't break there.
Line breaks in HTML are made using the <br> element.
<p>
This sentence is in the first line.<br>
This one is in the second.
</p>
You could use document.createElement("br") and append the element between two text nodes to create two lines, but there's a simpler way, innerText.
const elem = document.getElementById("demo");
elem.innerText = "First line\nSecond line"
<p id="demo"></p>

Related

appending User entered text using createTextNode method

Right now I am trying to figure out how to append CREATED text to a CREATED p element depending on what a user enters into an input text field.
If I set the text after the createTextElement method, it displays just fine when I click the button. BUT what I want is: the user enters text in the input field and then upon clicking the button, the text get's added to the end of the div tag with the id of "mydiv". Any help is appreciated.
HTML:
<body>
<div id="mydiv">
<p>Hi There</p>
<p>How are you?</p>
<p>
<input type="text" id="myresponse">
<br>
<input type="button" id="showresponse" value="Show Response">
</p>
<hr>
</div>
</body>
JAVASCRIPT:
var $ = function(id) {
return document.getElementById(id)
}
var feelings = function()
{
$("myresponse").focus();
var mypara = document.createElement("p");
var myparent = $("mydiv");
myparent.appendChild(mypara);
var myText = document.createTextNode($("myresponse").value);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
$("displayedresponse").appendChild(myText);
}
window.onload = function() {
$("showresponse").onclick = feelings;
}
You need to apply an argument to createTextNode function
You need to read the value of the input field so you can see the text.
Since you will reference mydiv on every click, i think moving mydiv variable to parent scope will suit you better
var $ = function (id) {
return document.getElementById(id)
}
let mydiv = $('mydiv');
$("showresponse").addEventListener('click', feelings);
function feelings() {
let textInput = $('myresponse').value;
var mypara = document.createElement("p");
var myText = document.createTextNode(textInput);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
mydiv.appendChild(mypara);
$("displayedresponse").appendChild(myText);
}

Adding br tag in innerHTML between text and image

In my javascript program I have created div and added image and some hardcoded text in div by using innerHTML. But I am trying to add dynamic br tag between text and image. First text should be displayed then want to line break and then image should be displayed. So created br and added but somehow it doesn't work. Can anyone correct me ?
code:
function useInnerHTML() {
var movieText2 = prompt("One of my favourite movies");
var textNode = document.createTextNode(movieText2);
ele.appendChild(textNode);
document.body.appendChild(ele);
var newDiv2 = document.createElement("div");
var br = document.createElement("br");
newDiv2.className = "green";
var pic = "A picture is worth a thousand words";
var text2 = '<img src=\'https://i.stack.imgur.com/meXYL.png\'>';
newDiv2.innerHTML = pic + text2;
document.body.appendChild(newDiv2);
document.body.appendChild(br);
}
useInnerHTML();
.pink {
background-color: pink;
}
.green {
background-color: #71e887;
}
my output:
![output][1]
Simply use
pic = "A picture is worth a thousand words <br>";
since by using .innerHTML the <br> tag will not be escaped and actually embedded into the HTML as a breakline Element.
Or
Use Template strings and insertAdjacentHTML
function addNewMovie() {
var movieName = prompt("One of my favourite movies").trim(); // Trim it!
if(!movieName) return; // do nothing if empty!
var movieTemplate = `
<div class="movie">
<h1>${movieName}</h1>
<div class="green">
A picture is worth a thousand words<br>
<img src='//placehold.it/100x100/0bf'>
</div>
</div>
`;
document.body.insertAdjacentHTML("beforeend", movieTemplate);
}
<button onclick="addNewMovie()">ADD NEW MOVIE</button>
...cleaner, nicer.
You are adding the <br> after the picture, try doing it like this:
newDiv2.innerHTML = pic + br + text2;
document.body.appendChild(newDiv2);

how do I dynamically create the id while creating the text box?

I'm looking at this fiddle: http://jsfiddle.net/npH8X/
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
addBox = function(){
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
anybody have javascript example like it, but showing exactly how I might give each of those boxes its own id either at its creation or right afterwards while I'm at it?
I want to create a writer's tool where they can type info into each box and then port all the inputs into one larger container afterwards, so the boxes need ids to do that...
thanks
All you need to do is set the .id property of the textbox after it is created, but before it is inserted to the DOM. This can correspond to a variable, and automatically increment based off of it:
var count = 3; // Corresponding to the existing textbox count
addBox = function() {
var textBox = document.createElement("textarea");
count++;
textBox.id = count;
document.getElementById("parent").appendChild(textBox);
console.log("New element's ID: " + textBox.id);
}
<div id='parent'>
<textarea id="1">txt1</textarea>
<textarea id="2">txt2</textarea>
<textarea id="3">txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
However, note that you don't need to give your <textarea> elements IDs in order to be able to target them. You use document.querySelectorAll() to return a collection of all textboxes, including those that have been dynamically created:
addBox = function() {
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
checkBoxes = function() {
console.log(document.querySelectorAll("#parent textarea"));
}
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
<button onClick="checkBoxes()">check boxes</button>
Hope this helps! :)
Comment Answer:
.querySelectorAll() simply returns a node list of all of the <textarea> elements. As such, you can access the fourth element with 3 as an index (as it starts from 0). document.querySelectorAll("#parent textarea")[3] corresponds to the fourth <textarea>, and you can retrieve its contents with the .value property:
addBox = function() {
var textBox = document.createElement("textarea");
document.getElementById("parent").appendChild(textBox);
}
var box4content;
getBox4 = function() {
if(document.querySelectorAll("#parent textarea")[3]) {
box4content = document.querySelectorAll("#parent textarea")[3].value;
}
console.log("The variable `box4content` has the value: " + box4content);
}
<div id='parent'>
<textarea>txt1</textarea>
<textarea>txt2</textarea>
<textarea>txt3</textarea>
</div>
<button onClick="addBox()">add textarea</button>
<button onClick="getBox4()">get box 4</button>

Stack at getting elements with javascript

I have the following html elements from which I have to get some specific texts,
example "John Doe"
I'm a newbie in javascript but have been playing with getElementById etc but I can't seem to get this one right.
<div id="name">
<p><span id="nameheading">name: </span> John Doe</p>
</div>
Bellow is What I have tried:
function askInformation()
{
var nameHeading = document.getElementById("nameheading");
var paragraph = document.getElementsByTagName("p").item(0).innerHTML ;
var name = paragraph[4];
console.log(name); // prints letter (n)
}
I need help please
If you want to get the text following the span in the following:
<div id="name">
<p><span id="nameheading">name: </span> John Doe</p>
</div>
You can use something like:
// Get a reference to the span
var span = document.getElementById('nameheading');
// Get the following text
var text = span.nextSibling.data;
However that is highly dependent on the internal structure, it may be best to loop over text node children and collect the content of all of them. You may also want to trim leading and trailing white space.
You could also get a reference to the parent DIV and use a function like the following that collects the text children and ignores child elements:
// Return the text of the child text nodes of an element,
// but not descendant element text nodes
function getChildText(element) {
var children = element.childNodes;
var text = '';
for (var i=0, iLen=children.length; i<iLen; i++) {
if (children[i].nodeType == '3') {
text += children[i].data;
}
}
return text;
}
var text = getChildText(document.getElementById('name').getElementsByTagName('p')[0]);
or more concisely for hosts that support the querySelector interface:
var text = getChildText(document.querySelector('#name p'));
var paragraph = document.getElementsByTagName("p").item(0).innerHTML ;
var name = paragraph.replace('<span id="nameheading">name: </span>','').trim(); // John Doe

Get content of span

how can I get the contents of span ?
I'm looking for a way for all of this to be vanilla, not jQuery
javascript (and a little jQuery)
var swear_words_arr=new Array("bad","evil","freak");
var regex = new RegExp('\\b(' + swear_words_arr.join('|') + ')\\b', 'i' );
function validate_user_text() {
var text = document.getElementById('myInput');
text.text();
if(regex.test(text)) {
window.location="http://www.newlocation.com";
return false;
}
}
var myVar=setInterval(function(){validate_user_text()},1000);change
here's my html
<div id="textArea">
<span id="myInput" contenteditable="true">kfjdkfj</span>
</div>
<br />
<form name="form1" method="post" action="">
<textarea rows="3" cols="40" name="user_text" style="border:2 solid #808080; font-family:verdana,arial,helvetica; font-weight:normal; font-size:10pt" onclick="select_area()"></textarea>
<br />
<input type="button" value="Submit" onclick="return validate_user_text();"></form>
Thank You
Give this a shot:
var input = document.getElementById("myInput");
var text = input.innerHTML;
You can use textContent
Taken from MDN:
// Given the following HTML fragment:
// <div id="divA">This is <span>some</span> text</div>
// Get the text content:
var text = document.getElementById("divA").textContent;
// |text| is set to "This is some text".
// Set the text content:
document.getElementById("divA").textContent = "This is some text";
// The HTML for divA is now:
// <div id="divA">This is some text</div>
There is an issue here:
var text = document.getElementById('myInput');
text.text();
You never assigned the text of the input to any variable.
Following your pattern above, you could do:
var txt = document.getElementById('myInput'),
txt = text.text();
The second variable updates the previous variable 'txt' to hold the text of the original 'txt' variable, which was a selector.
You could do this as well (vanilla javascript, jsfiddle):
var txt = document.getElementById('myInput').innerHTML;
//or
var txt = document.getElementById('myInput').textContent;
Instead of using...
text.text();
Try using...
text.innerHTML;
I've only found .text() to work when you're using a jQuery selector.
$('#myInput').text();
var text = (document.getElementById("myInput")).innerHTML
or the abridged form:
var text = $('#myInput').text()

Categories

Resources