I'm new to javascript and programming, and I am trying to create a webpage where the user can input the data on the page, and then I wrap it around HTML code to create an HTML template. I've tried using a couple methods but the document.write() command seems to be working for what I need. However, I'm trying to add the HTML tags around the input text and not getting a usable format.Full code below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8"/>
</head>
<body>
<h1>Title<input type="textarea" id="top_field" value="" style="width:100px; height:30px"></h1>
<br/>
<h2>Position/Proposal<input type="textarea" id="subtitle_field" value="" style="width:100px; height:30px"></h2>
<br/>
<p>Body Text: <input type="textarea" id="field1" value="" style="width:100px; height:30px"></p><br/>
<button id="sub_button" type="button" onclick="myFunction()">Copy</button>
<div id="full_code" hidden>
<p id="must_have" value='text'><!DOCTYPE> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta charset="utf-8"/><br></head>
</p>
<p id="less_than"><</p>
<p id="more_than">></p>
</div>
<script>
function myFunction() {
//const html_array = ["<!DOCTYPE>", "<html>", "<head>", "<meta name="viewport" content="width=device-width, initial-scale=1"/>", "<meta charset="utf-8"/>", "</head>"];
if(document.getElementById("field1").value != "" || document.getElementById("top_field").value != "" || document.getElementById("subtitle_field").value != ""){
let p_elem = document.getElementById("less_than").innerText + "p" + document.getElementById("more_than").innerText;
let pend = document.getElementById("less_than").innerHTML + "/p" + document.getElementById("more_than").innerHTML;
let body = document.getElementById("less_than").innerHTML + "body" + document.getElementById("more_than").innerHTML;
let bodyend = document.getElementById("less_than").innerHTML + "/body" + document.getElementById("more_than").innerHTML;
var top_text = document.getElementById("must_have").innerText;
var newParagraph2 = document.createElement("p"); //creates a new paragraph element
var newText2 = document.createTextNode(top_text); //creates text along with output to be displayed
newParagraph2.appendChild(newText2); //created text is appended to the paragraph element created
document.body.appendChild(newParagraph2); // created paragraph and text along with output is appended to the document body
var main_text = document.getElementById("field1").value;
var newParagraph = document.createElement("p"); //creates a new paragraph element
var newText = document.createTextNode(main_text); //creates text along with output to be displayed
newParagraph.appendChild(newText); //created text is appended to the paragraph element created
document.body.appendChild(newParagraph); // created paragraph and text along with output is appended to the document body*/
var title_text = document.getElementById("top_field").value;
var newParagraph3 = document.createElement("p"); //creates a new paragraph element
var newText3 = document.createTextNode(title_text); //creates text along with output to be displayed
newParagraph3.appendChild(newText3); //created text is appended to the paragraph element created
document.body.appendChild(newParagraph3); // created paragraph and text along with output is appended to the document body
var less_symbol = document.getElementById("less_than").value;
var newParagraph4 = document.createElement("p"); //creates a new paragraph element
var newSymbol = document.createTextNode(less_symbol); //creates text along with output to be displayed
newParagraph4.appendChild(newSymbol); //created text is appended to the paragraph element created
document.body.appendChild(newParagraph4); // created paragraph and text along with output is appended to the document body*/
document.writeIn(newParagraph2.innerText); //
}
else{
document.write("No text");
}
}
</script>
</body>
</html>
By now I'm able to read the text input and output in the same page below, but not able to add anything around the appended child or make the original tags above appear vertically. If someone can lead me in the right direction on method I should be using I would greatly appreciate it.
I would suggest NOT writing html strings with document.write. Instead, you can use createElement and appendChild to create html tags and add them to the page. It's much more readable and less likely to cause syntax errors in your html tags.
For example, to create a div that contains text from your inputfield:
let fieldValue = document.getElementById("myfield").value
let div = document.createElement("div")
div.innerHTML = fieldValue
document.body.appendChild(div)
Hope this generic example points you in the right direction!
Related
so im trying to make a list of the input from the user and i keep getting this error
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ToDo</title>
</head>
<body>
<h1>To Do List</h1>
<label>Enter What You Have To Do:</label>
<br>
<br>
<input type="text" id="toDo">
<br>
<br>
<button type="button" id="myButton">Submit</button><br>
<ul id="list"></ul>
<script src="todojs.js"></script>
</body>
</html>
javascript
document.getElementById('myButton').onclick = function () {
const doIt = document.getElementById('toDo').value;
const li ='<li>' + doIt + '</li>';
document.getElementById('list').appendChild(li);
document.getElementById('toDo').value = '';
}
Error
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at document.getElementById.onclick
appendChild expects a Node Element. You are passing a string.
If you want to append a string, you can use the insertAdjacentHTML function.
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
document.getElementById('myButton').onclick = function () {
const doIt = document.getElementById('toDo').value;
const li ='<li>' + doIt + '</li>';
document.getElementById('list').insertAdjacentHTML('beforeend', li);
document.getElementById('toDo').value = '';
}
const li = document.createElement("li");
li.innerHTML(doIt);
should do the trick instead of the one liner
if you pass a string, that string isn't a node or a real element present in the DOM, it wouldn't work.
so simply just programmatically create one element! using document.createElement()
change the text inside it, using document.textContent
try to not use innerHTML because is DANGEROUS, someone can insert in the input some malicious code scripts. textContent is more safe
one more thing, use .addEventListener()
instead of .onclick,
because if you have more event listener in one time, .onclick sometimes don't work, with .addEventListener() you can make 2 or more events work in one time.
for inserting before you can use this: https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore , just read the documentation I linked to you, and you are done!
I hope this help you!
one more thing:
if you want more custom UI,
you can write a copy of all your elements inside a <div>,
and then insert it inside a <template> tag manually...
the result is: now you have a reusable component with just regular HTML, JS
so the previus document.createElement(); it will become Node.cloneNode()
more details here: https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
let btn = document.getElementById('myButton');
let list = document.getElementById('list');
let inputEl = document.getElementById('toDo');
btn.addEventListener('click', () => {
const getliValue = inputEl.value;
const newLi = document.createElement('li');
newLi.textContent = getliValue;
list.appendChild(newLi);
inputEl.value = '';
});
<h1>To Do List</h1>
<label>Enter What You Have To Do:</label>
<br><br>
<input type="text" id="toDo">
<br><br>
<button type="button" id="myButton">Submit</button>
<br>
<ul id="list"></ul>
<script src="script.js"></script>
I have created javascript program in that I have created div tag in body and prompt in order to accept text from user after that I have created div and want to add prompt text to div.The new div should be display before already created one and for that I have used insertBefore(). I tried to get the value in console and I am getting values in console. but my program is not working as per expectation.
code:
<!DOCTYPE html>
<html>
<head>
<title>trail</title>
<meta charset="utf-8">
<style type="text/css">
.pink{
background-color: pink;
}
.green{
background-color: #71e887;
}
</style>
<script type="text/javascript">
var movieText = prompt("What movie do you like?");
var newDiv = document.createElement("div");
parent = newDiv.parentNode;
newDiv.className = "green";
var text = document.createTextNode(movieText + " is a good movie");
newDiv.innerHTML = text;
newDiv.appendChild(text);
var beforeMe = document.getElementById("div1");
document.body.insertBefore(newDiv, beforeMe);
</script>
</head>
<body>
<br>
<div class="pink" id = "div1">
I love watching movies <br/>
This is one of my favorite movie:
</div>
</body>
</html>
my output:
[![enter image description here][1]][1]
expected output:
[![enter image description here][2]][2]
As #pari mention, you are inserting a text node objet using innerHTML. This function will performance a .toString() to the text node. That is way you are receiving the output [object text]. If you are required to use innerHTML then just go with .innerHTML(movieText + " is a good movie")
Or you can use the text node like this :
var textNode = document.createTextNode(movieText + " is a good movie");
newDiv.appendChild(textNode);
but do not use both at the same time.
I have a variable that java-script copied from google spreadsheet and I am also able to display it into html form using <textarea>. My problem is that i also have a link in form of a variable that I want to hyperlink with my previous variable:-
I think my code will explain a little more:-
Javascript copied a cell value that is "Hello there, I am groot"
code.gs:-
function fetchValues(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1"); //Enter your sheet Name
var data = sheet.getRange("B2").getValues();
return data;
}
now I want to hyperlink the "there" part of my variable and display into my HTML.
Here is my iNdex.html :-
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<textarea class="js-copytextarea" style="width:100%;" rows="5" id="a" Value"a" name="a"></textarea>
<p>
<button class="js-textareacopybtn">Copy Textarea text</button>
</p>
<script>
function displayValue3(data){
document.getElementById("a").value=data;
}
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
copyTextareaBtn.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('.js-copytextarea');
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
});
</script>
</html>
Now I just don't know how to add that variable link into "there" from "Hello there, I am groot" and display the text into text area.
You can't add link inside a textarea, the textarea can only display text content. You can use label or if you want to edit the content you can use div with contentEditable attribute.
<div class="js-copytextarea" style="width:100%;" contentEditable id="content" name="a"></div>
function displayValue3(data){
document.getElementById("content").innerHTML="<a href='"+data+"'>there</a>"; //I hope data has the valid link
}
I have looked for duplicate questions, however many refer to adding data to XML
please forgive me if I have missed something here but I need some help
so far I have this:
html page
<!DOCTYPE html>
<html>
<head>
<title>Template</title>
<script type="text/javascript" src="script/controlpanelAdmin.js"></script>
<script type="text/javascript" src="script/controlpanelModerator.js"></script>
<script type="text/javascript" src="script/jquery-1.12.0.js"></script>
<link rel="stylesheet" href="script/css.css" />
</head>
<body>
<fieldset id="control_panel">
<legend>Control Panel</legend>
</fieldset>
<p id="content"> Content </p>
</body>
</html>
controlpanelAdmin.js
window.onload = function() {
var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("admin");
var br = document.createElement("br");
var txt = document.createTextNode("Admin Control Panel");
controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}
controlpanelModerator.js
window.onload = function() {
var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("mod");
var br = document.createElement("br");
var txt = document.createTextNode("Moderator Control Panel");
controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}
When the page loads, 'Admin Control Panel' is written into the fieldset tag
but is then replaced by: 'Moderator Control Panel'
I cannot for the life of me think how to append both lines (and maybe other data as well) into one element
When the page loads, 'Admin Control Panel' is written into the fieldset tag but is then replaced by: 'Moderator Control Panel'
That can't happen. Admin Control Panel should never appear in the page.
script/controlpanelAdmin.js loads. It causes a value to be assigned to window.onload.
script/controlpanelModerator.js loads. It causes that value to be overwritten with a new one.
The page finishes loading
The load event fires
The function defined in script/controlpanelModerator.js is called
Don't assign values to window.onload. Use addEventListener instead.
addEventListener("load", function () { ... });
You've got two onload functions competing. Can you merge them into one function?
Im learning JavaScript and i have problem with DOM methods.
HTML
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="DOM_Ponovno.js"></script>
</head>
<body>
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
</body>
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
document.write(tmpTag[i].textContent);
}
}
If i follow the tutorial its ok, but i wanted to display all elements by tag name p. I want to display all paragraphs stored in tmpTag.
Someone please explain:
How can ( why cant) display all elements with tag name p ?
How can (why cant) display 3x p tag from variable tmpTag ?
Tried to change to Array with prototype.slice.call method but no success.
You know like Java stuff loop through display/change at index etc..
Thank you :)
Hi and thanx for fast answers.. Sory about the function name it was for testing... I just want to display all elements by tag name p. This code displays only first element and i counter in for loop stops at 1. Why cant i get other 2 paragraph elements ?
Im using document.write like system.out.print in Java to see whats in array. I know if i wanna change i need innerHTML.
If you are wanting to update each paragraph, do not use document write. Try the following:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
tmpTag[i].innerHTML = "Your new updated text to change it to for tag index " + i + "...";
}
}
As #Juhana mentioned, the moment you start your loop you overwrite the document using document.write, so all your p tags get removed from the document and replaced by the text in the first paragraph and then your function fails, as the now-empty objects don't have any textContent property. You could concatenate all the contents and write it once:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var print = '';
for(var i = 0;i< tmpTag.length;i++) {
print += tmpTag[i].textContent;
}
document.write(print)
}
But actually, just don't use document.write - SO snippets don't even allow it anymore! Here a way with a div as output:
var output = document.getElementById('output');
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
output.textContent += tmpTag[i].textContent;
}
}
<div>
<p id="demo" >this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
<div id="output"></div>
I'm not sure what you're trying to do but you can add another div for result with id='result' and append result you want to it, check following example.
Hope this will help.
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var result = document.getElementById('result');
for(var i = 0;i< tmpTag.length;i++) {
result.innerHTML += tmpTag[i].textContent+'<br>';
}
}
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
<br>
<div id="result" ></div>
</div>