For example, replace the word "Europe" in "I want to go to Europe" with a text field.
My following attempt doesn't work.
let sentence = "I want to go to Europe"
let i = `<input type="text" size="6">`
let s = sentence.replace(/Europe/,i)
In the browser, it displays <input type="text" size="6"> instead of the desired input field.
Question is not clear. I assume you're trying to do the following:
let sentence = "I want to go to Europe";
let i = `<input type="text" size="6">`;
let s = sentence.replace(/Europe/,i);
document.getElementById('sentence-wrapper').innerHTML = s;
<div id="sentence-wrapper"></div>
You should use .innerHTML instead .innerText. This is the comparison :
let div1 = document.getElementById("sentence1");
let div2 = document.getElementById("sentence2");
let sentence = "I want to go to Europe"
let i = `<input type="text" size="6">`;
let s = sentence.replace(/Europe/,i);
div1.innerHTML = s;
div2.innerText = s;
<div id="sentence1"></div>
<div id="sentence2"></div>
To replace a word in a sentence with an input field, you can try this:
let input = document.getElementById("country");
let button = document.getElementById("replace");
let div = document.getElementById("sentence");
let sentence = "I want to go to Europe";
div.innerHTML = sentence;
//let i = `<input type="text" size="6">`;
button.onclick = function() {
sentence = div.innerHTML;
let s = sentence.replace(sentence.split(" ").at(-1),input.value);
div.innerHTML = s;
}
<input id="country" type="text" />
<button id="replace">Replace</button>
<div id="sentence"></div>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<input type="text" size="6" id='text'>
<p id="inpVal"></p>
</body>
<script>
let inpVal = document.getElementById('text')
inpVal.addEventListener('input',(e)=>{
let sentence = `I want to go to ${e.target.value}`
document.body.querySelector('#inpVal').innerHTML = sentence
})
</script>
</html>
Related
What have I done wrong? Here is what the result tells me:
Uncaught ReferenceError: addToDoButton is not defined
Here is my JavaScript:
let addToDo = document.getElementById("edit_button");
let toDoContainer = document.getElementById("to_do_container");
let inputField = document.getElementById("inputField");
addToDoButton.addEventListener("click", function(){
var paragraph = document.createElement("p");
paragraph.classList.add("paragraph-styling");
paragraph.innerText = inputField.value;
toDoContainer.appendChild(paragraph);
inputField.value = " ";
paragraph.addEventListener("click", function(){
paragraph.style.textDecoration = "line-through";
})
paragraph.addEventListener("dblclick", function(){
paragraph.removeChild(paragraph)
})
})
Here is my HTML:
<html>
<head>
<link rel="stylesheet", href="style.css">
<h1 class="tdl_header">TO DO LIST</h1>
</head>
<body class="body">
<div class="container">
<input id="inputField" type = "text"
placeholder="add your list">
<button id="addToDo"> + </button>
<div class="to-dos" id="toDoContainer" >
</div>
</div>
<script src="to_do_list.js"></script>
</body>
</html>
let addToDo = document.getElementById("edit_button");
let toDoContainer = document.getElementById("to_do_container");
let inputField = document.getElementById("inputField");
addToDoButton.addEventListener("click", function() {
var paragraph = document.createElement("p");
paragraph.classList.add("paragraph-styling");
paragraph.innerText = inputField.value;
toDoContainer.appendChild(paragraph);
inputField.value = " ";
paragraph.addEventListener("click", function() {
paragraph.style.textDecoration = "line-through";
})
paragraph.addEventListener("dblclick", function() {
paragraph.removeChild(paragraph)
})
})
<html>
<head>
<link rel="stylesheet" , href="style.css">
<h1 class="tdl_header">TO DO LIST</h1>
</head>
<body class="body">
<div class="container">
<input id="inputField" type="text" placeholder="add your list">
<button id="addToDo"> + </button>
<div class="to-dos" id="toDoContainer">
</div>
</div>
<script src="to_do_list.js"></script>
</body>
</html>
You called your variable addToDo but want to add the listener to addToDoButton which doesn't exist.
EDIT:
As #Beriu mentioned, the id of the button also doesn't match the string in the selector.
You have two issues there:
you want to select a button wiht getElementById('edit_button') which doesn't exists
you want to addEventListener to a DOM element which can't be selcted
Solution:
let addToDo = document.getElementById("addToDo");
let toDoContainer = document.getElementById("to_do_container");
let inputField = document.getElementById("inputField");
addToDo.addEventListener("click", function() {
// your code
})
I would suggest you attach your event handler for the click and double click on the "tasks" to the container, then it is easier to use the event.target for the action to take place.
I did some rework of class and id to make them more consistent and match the event handler attachment here also.
I also do not append "blank" tasks.
function handleToDoPlus(event) {
let inputField = document.getElementById("input-field");
let newValue = inputField.value;
let hasValue = newValue.length > 0
event.target.nextElementSibling.innerText = hasValue ? "" : "No Value Entered";
if (hasValue) {
let paragraph = document.createElement("p");
paragraph.classList.add("paragraph-styling");
paragraph.innerText = newValue;
let toDoContainer = document.getElementById("to-do-container");
toDoContainer.appendChild(paragraph);
inputField.value = "";
}
}
function handleDoubleClick(event) {
console.log('double click!');
if (event.target.className === 'paragraph-styling') {
event.currentTarget.removeChild(event.target)
}
}
function handleClickToDone(event) {
console.log('Click!');
if (event.target.className === 'paragraph-styling') {
event.target.style.textDecoration = "line-through";
}
}
let addToDo = document.getElementById("add-to-do");
addToDo.addEventListener("click", handleToDoPlus);
let toDoContainer = document.getElementById("to-do-container");
toDoContainer.addEventListener("dblclick", handleDoubleClick);
toDoContainer.addEventListener("click", handleClickToDone);
//let inputField = document.getElementById("input-field");
.error-message {
color: #FF0000;
}
<div class="container">
<input id="input-field" type="text" placeholder="add your list">
<button id="add-to-do"> + </button> <span class="error-message"></span>
<div id="to-do-container" class="to-dos">
</div>
</div>
I have a string "yes\no↵abc" as input in an HTML text area.
On performing JSON.stringify, it returns me "yes\no\nabc".
Now I need to display the same content back in a textarea in HTML. To replace the "\n" I get after JSON.stringify (Stringify converts ↵ to \n ) I used the following regex str2.replace(/\n/g, "\n").
Now how do I escape the \ I am getting.
I have attached code to below
function myFunction() {
var str = document.getElementById("para1").value
var str2 = JSON.stringify(str);
document.getElementById("para").innerText = "Stringified text \n" +str2;
var res = str2.replace(/\\n/g, "\n");
document.getElementById("para2").innerText = "Replaced text \n" + res;
}
<html>
<body>
Click the button</p>
<p id="demo">Demo!</p>
<textarea id = "para1">
</textarea>
<textarea id = "para">
</textarea>
<textarea id = "para2">
</textarea>
<textarea id = "para4">
</textarea>
Click
<button onclick="myFunction()">Try it</button>
</body>
</html>
The input to the text area should be:
yes\no
abc
It is very specific to what you want and has risk of breaking in other scenarios may be, but takes care of what you want in this case.
function myFunction() {
var str = document.getElementById("para1").value
var str2 = JSON.stringify(str);
document.getElementById("para").innerText = "Stringified text \n" +str2;
var res = str2.replace(/(\\\\)/g, "\\ ");
var res = res.replace(/\\n/g, "\n");
var res = res.replace(/\\ /g, "\\");
document.getElementById("para2").innerText = "Replaced text \n" + res;
}
<html>
<body>
Click the button</p>
<p id="demo">Demo!</p>
<textarea id = "para1">
</textarea>
<textarea id = "para">
</textarea>
<textarea id = "para2">
</textarea>
<textarea id = "para4">
</textarea>
Click
<button onclick="myFunction()">Try it</button>
</body>
</html>
Let me know if that works. Cheers!
To achieve expected result, use below option
var res = str2.replace(/\\na/g, "\n a");
https://codepen.io/nagasai/pen/gvedQY
This my code..
<!DOCTYPE html>
<html>
<head>
<script>
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name ").value;
var school_site= document.getElementById("school_site ").value;
var content= "<h2>Student Details:</h2>"+"/n"+
"<div align='justify'>
<p>"+name+"is studing in "+school_name+"</p>"+"/n"+
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p></div>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
</head>
<body>
Privacy Policy Page
<p>Name:</br> <input type="text" name="name" id="name"></p>
<p>School Website:</br> <input type="text" name="school_site" id="school_site"></p>
<p>School Name:</br> <input type="text" name="school_name" id="school_name"></p>
<button id="click" onclick="generate()">Generate</button>
<div style="display:none" id="show">
<div style="height:200px; width:540px; overflow:auto;" id="displayarea">
</body>
</html>
"content" is the javascript variable.
I need to assign HTML code as value for "content" variable,
And i also need to add some Javascript variable inside the HTML
code,
How to add javascript variable in html Hypertext link?
There are many ways to achieve this. For a simple use-case, you can use an array of string to perform work and at the end you can join with "" or "\n".
var template = [
"<h2>Student Details:</h2>",
"<div align='justify'><p>"+name+"is studing in "+school_name+"</p>",
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p></div>"
].join("<br/>");
For more complex case, I will say use jquery or Plain JavaScript method. As given below.
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
//jQuery:
var node = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
);
//Plain JavaScript
var h2 = document.createElement("h2");
h2.textContent = "Student Details:";
var div = document.createElement("div");
var p1 = document.createElement("p");
p1.textContent = name+"is studing in "+school_name;
var p2 = document.createElement("p");
p2.textContent = "Visit site: ";
div.appendChild(p1);
div.appendChild(p2);
//add attribute node
var node = document.getElementById("div1");
var a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);
//Once done return as string
return div.outerHTML;
}
You have extra space in id in school_name and school_site`.
So it is not being recognized and you are getting exception. Also your syntax to concatenate string is also incorrect.
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
Your full javascript code would be like this
<script>
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
var content= "<h2>Student Details:</h2>"+"/n"+
"<div align='justify'>"+
"<p>"+name+"is studing in "+school_name+"</p>"+"/n"+
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
You can write a string on multiple lines using template literals, i.e. using the character " ` ".
You can easily integrate variables using ${yourVar} in the template literal
Example:
let lit = "literal";
var content = `This string
uses a template ${lit}`;
console.log(content);
Note: this is an ES6 feature, aka the not so new JavaScript that is not yet fully supported by browsers. To make this code compatible with older browsers, use a transpiler like babel
You have to use <br> instead of '/n' while assigning to javascript variable.
The problem as I see it is you have hit enter in the mid of string and you have extra space in the id selector.
Don't hit enter or use tilt ` to declare string instead of quotes.
<!DOCTYPE html>
<html>
<head>
<script>
function generate() {
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site = document.getElementById("school_site").value;
var content = "<h2>Student Details:</h2>" +
"<div align='justify'><p>" + name + "is studing in " + school_name + "</p>" +
"<p>Visit site: <a href='http://" + school_site + "'>http://" + school_site + "</a></p></div>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
</head>
<body>
Privacy Policy Page
<p>Name:</br>
<input type="text" name="name" id="name">
</p>
<p>School Website:</br>
<input type="text" name="school_site" id="school_site">
</p>
<p>School Name:</br>
<input type="text" name="school_name" id="school_name">
</p>
<button id="click" onclick="generate()">Generate</button>
<div style="display:none" id="show">
<div style="height:200px; width:540px; overflow:auto;" id="displayarea">
</body>
</html>
Suggestion : No need to use /n for new line, h2 is block element no need of break too.
Something weird is happening here.
My website is using javascript to create dynamic divs, but although they are entered into the DOM (at least this is what I think), javascript returns null when calling that div.
This is the javscript code which is loaded before </body>
function AddPlayer(){
var name = document.getElementById('name').value;
createBox(name);
};
function createBox(name){
var span = document.createElement('span');
span.id = name;
span.innerHTML = name;
document.getElementById("gameArea").appendChild(span);
var span = document.createElement('span');
span.id = "score-" + name;
span.innerHTML = "0";
document.getElementById("gameArea").appendChild(span);
var inputSText = document.createElement('input');
inputSText.type = "button";
inputSText.value = "Add Points";
inputSText.onclick = function(){AddPoints(name);};
document.getElementById("gameArea").appendChild(inputSText);
};
function AddPoints(player){
document.load(document.getElementById("#score-"+ player).innerHTML = "Please work");
};
<html>
<head>
<title>Game Score Keeper</title>
</head>
<body>
<h2>Game Score Keeper</h2>
<input type="text" id="name" />
<input type="button" value="Add Player" onclick="AddPlayer()" />
<div id="gameArea">
</div>
<script src="index.js"></script>
</body>
</html>
Here is the jsfiddle of this project http://jsfiddle.net/jwmm6rk7/
You need to pass the id of the element to document.getElementById. That is, without the hash (#) symbol.
function AddPoints(player) {
document.load(document.getElementById("score-" + player).innerHTML = "HELLO");
};
lookslike you were jQuery user, you used # and name instead of player
function AddPoints(player) {
document.getElementById("score-" + player).innerHTML = "HELLO";
};
I'm trying to print an array to a textarea in JavaScript. My current code only prints the first element instead of all four, and I don't know why.I have tried using a regular for loop as well, but that doesn't make a difference.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var listArray = function()
{
var people = ["Ben", "Joel", "Mary", "Tina"];
var scores = [88, 98, 100, 78];
for (var key in people)
{
var obj = people[key];
var num = scores[key];
var string = obj + ", " + num + "\n";
document.getElementById("box").innerHTML = string;
}
}
window.onload = function()
{
document.getElementById("show_score").onclick = showHighScore;
document.getElementById("list_array").onclick = listArray;
}
</script>
</head>
<body>
<form id="high_score" name="high_score" action="highScore.html" method="get">
<label>Results</label>
<br>
<textarea cols="50" rows="4" id="box"></textarea>
<br>
<input type="button" value="List Array" id="list_array" onclick="listArray">
<br>
<input type="button" value="Show Best Score" id="show_score" onclick="showHighScore">
</form>
</body>
</html>
That is because of this line
document.getElementById("box").innerHTML = string;
So what you are saying, replace the content of textbox with the content of string. So at the end it just have the value of last element.
use this instead
document.getElementById("box").innerHTML += string;
So it will append the next record after previous one.
There is one more problem, on 23rd line it sasys showHighScore is not defined.