Adding HTML from JavaScript removes written texts from input - javascript

I'm developing a web page by means of which user will add questions and answers. To add a new question the user clicks on the button and new div is added to container.
The problem is that when a new text-area is added, the text written in the other text-areas is removed.
View of filled text-area before clicking the button
View of text-area after clicking the button
Code:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
const template = '<form class="eachtest">' +
'<textarea id="question" rows="4" cols="80" placeholder="Sual"></textarea>' +
'<br><strong> A </strong> ' +
'<textarea class="answer" rows="4" cols="80" placeholder="Cavab"></textarea><br>' +
'</form>';
function on_click() {
document.querySelector('.container').innerHTML += template;
}
</script>
</head>
<body>
<div class="container"></div>
<button id="add" type="button" name="button" onclick="on_click()">add</button>
</body>
</html>

innerHTML rebuild the whole content. Try the following:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
const template = '<form class="eachtest"><textarea id="question" rows="4" cols="80" placeholder="Sual"></textarea><br><strong> A </strong> <textarea class="answer" rows="4" cols="80" placeholder="Cavab"></textarea><br></form>';
function on_click() {
document.querySelector('.container').insertAdjacentHTML('beforeend', template);
}
</script>
</head>
<body>
<div class="container">
</div>
<button id="add" type="button" name="button" onclick="on_click()">add</button>
</body>
</html>
For more info on innerHTML, click here

As you should avoid using inline JS and CSS, I propose you the following:
Create a hidden div id="template" in your HTML,
Use JS to append its content after your container when you click the "add" button.
I also changed your id="question" to class="question" as you can add multiple ones.
const template = document.querySelector('#template').innerHTML;
var container = document.querySelector('.container');
document.querySelector('#add').onclick = function() {
container.insertAdjacentHTML('beforeend', template);
}
#template {
display: none;
}
<html lang="en" dir="ltr">
<body>
<div class="container"></div>
<button id="add" type="button" name="button">Add</button>
<div id="template">
<form class="eachtest"><textarea class="question" rows="4" cols="80" placeholder="Sual"></textarea><br> <strong> A </strong><textarea class="answer" rows="4" cols="80" placeholder="Cavab"></textarea><br></form>
</div>
</body>
</html>
Hope it helps.

Use Jquery append() :D
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
const template = '<form class="eachtest"><textarea id="question" rows="4" cols="80" placeholder="Sual"></textarea><br><strong> A </strong> <textarea class="answer" rows="4" cols="80" placeholder="Cavab"></textarea><br></form>';
function on_click() {
$('.container').append(template)
}
</script>
</head>
<body>
<div class="container">
</div>
<button id="add" type="button" name="button" onclick="on_click()">add</button>
</body>
</html>

Related

Remove dynamically created elements in a form

I know this is a basic questions, but I am working on making a dynamic form and was having a bit of trouble figuring out how to delete elements that share the same class. I have looked around on the web and other posts for a means to accomplish this, but still was unable to figure it out.
I am new to this so I apologize for the basic question. Below, I have pasted the relevant code and my attempt at this. Would anyone be able to assist me?
var ingCounter = 1;
var dirCounter = 1;
var limit = 10;
function addIngredient(divName){
if (ingCounter == limit) {
alert("You have reached the add limit");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement('directionSet');'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
ingCounter++;
}
}
function addDirection(divName){
if (dirCounter == limit) {
alert("You have reached the add limit");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' type='button'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
dirCounter++;
}
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homemade</title>
<!-- Required program scripts -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<!-- Style Sheets-->
<link rel="stylesheet" href="/styles/navBarStyle.css">
<link rel="stylesheet" href="/styles/myRecipesStyle.css">
<link rel="stylesheet" href="/styles/createRecipeStyle.css">
<link rel="stylesheet" href="/styles/errorMessageStyle.css">
</head>
<body>
<!-- Background image -->
<img id="background" src="/images/foodBackground.jpg" alt="">
<div id="newRecipeContainer">
<div id="closeButtonContainer">
<div id="backButton"><a id="back" href="/recipes/myRecipes">← My Recipes</a></div>
</div>
<form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
<label id="formSubHeading">Create Your Homemade Recipe</label>
<%- include('../_partial/_messages'); -%>
<div id="recipeNameContainer">
<label id="recipeNameLabel">Title</label>
<input id="recipeNameInput" type="text" name="recipeName">
</div>
<div id="recipeImage">
<label id="recipeImageLabel">Add An Image of Your Meal</label>
<input id="recipeImageInput" type="file" accept="image/*" name="recipeImage"/>
<label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
</div>
<div id="recipeDescription">
<label id="recipeDescriptionLabel">Description</label>
<textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
</div>
<div class="ingredientsContainer">
<label id="ingredientsLabel">Ingredients</label>
<button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>
<div id="allIngredients">
<div class="ingredientSet">
<input class="ingredientInput" type="text" name="ingredients[]">
</div>
</div>
</div>
<div class="directionsContainer">
<label id="directionsLabel">Directions</label>
<button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>
<div id="allDirections">
<div class="directionSet">
<input class="directionInput" type="text" name="directions[]">
</div>
</div>
</div>
<div id="createRecipeButtonContainer">
<button id="createRecipeButton" type="submit">Create Recipe</button>
</div>
</form>
</div>
</body>
<!-- Required scripts to run app -->
<script src="/controls/newRecipeControl.js"></script>
<script src="/controls/errorMessageControl.js"></script>
</html>
Thanks for any help.
In your code you are using getElementById but there is no id called directionSet its a class.
You can simply use parentElement and remove to remove the newly added dynamic inputs by calling an onClick function.
In the onClick function removeElement() - this refers to the elements we have clicked and it will remove from the form.
var ingCounter = 1;
var dirCounter = 1;
var limit = 10;
function addIngredient(divName) {
if (ingCounter == limit) {
alert("You have reached the add limit");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement(this);'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
ingCounter++;
}
}
function addDirection(divName) {
if (dirCounter == limit) {
alert("You have reached the add limit");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' onClick='removeElement(this);' type='button'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
dirCounter++;
}
}
function removeElement(elementId) {
// Removes an element from the document
elementId.parentElement.remove()
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homemade</title>
</head>
<body>
<!-- Background image -->
<div id="newRecipeContainer">
<div id="closeButtonContainer">
<div id="backButton"><a id="back" href="/recipes/myRecipes">← My Recipes</a></div>
</div>
<form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
<label id="formSubHeading">Create Your Homemade Recipe</label>
<div id="recipeNameContainer">
<label id="recipeNameLabel">Title</label>
<input id="recipeNameInput" type="text" name="recipeName">
</div>
<div id="recipeImage">
<label id="recipeImageLabel">Add An Image of Your Meal</label>
<input id="recipeImageInput" type="file" accept="image/*" name="recipeImage" />
<label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
</div>
<div id="recipeDescription">
<label id="recipeDescriptionLabel">Description</label>
<textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
</div>
<div class="ingredientsContainer">
<label id="ingredientsLabel">Ingredients</label>
<button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>
<div id="allIngredients">
<div class="ingredientSet">
<input class="ingredientInput" type="text" name="ingredients[]">
</div>
</div>
</div>
<div class="directionsContainer">
<label id="directionsLabel">Directions</label>
<button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>
<div id="allDirections">
<div class="directionSet">
<input class="directionInput" type="text" name="directions[]">
</div>
</div>
</div>
<div id="createRecipeButtonContainer">
<button id="createRecipeButton" type="submit">Create Recipe</button>
</div>
</form>
</div>
</body>
</html>

Why XSS doesn't work at a created HTML Page?

Hello I'm practice on XSS-Attack in an HTML Page that I created, but it doesn't work for me.
This is the HTML Page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Try to XSS this!</title>
<script language="javascript" type="text/javascript">
var send = function () {
var data = document.getElementById("msg").value;
document.getElementById("demo").innerHTML = data;
}
</script>
</head>
<body>
<p>Enter an XSS exploit here:</p>
<textarea id="msg" rows="10" cols="20"></textarea>
<br />
<input type="button" id="send" onclick="send();"/>
<br>
<p id="demo"></p>
</body>
</html>
This is the XSS-Exploit (I write it in the <textarea>):
hello</p>
<script>alert("XSS");</script>
<p>
And this is the result (I show the <p id="demo"></p> part):
<p id="demo">
"hello"
<p></p>
<script>alert("XSS");</script>
<p></p>
</p>
And the command alert("XSS"); doesn't work. What did I do wrong?
Script tags only run on page load; when you dynamically inject them into the page, script tags aren't run. The common bypass to this is to use onerror or onload like <img src=x onerror='alert(1)'> or <svg onload='alert(1)'></svg>

Why won't this code work to get the text from a HTML textbox and display it in a paragraph?

Why won't the code display the text from the textbook in the paragraph tag? I tried to take the code from the text box by using the onclick command and the function getVal() but it won't work.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="test.js">
function getVal1(){
var text = document.getElementById('text').value;
var par = document.getElementById('par');
par.innerHTML=text
}
</script>
</head>
<body>
<form>
<input type="text" id="text">
<input type="submit" value="Submit" onclick="getVal1()">
</form>
<p id="par"></p>
</body>
</html>
It cant work because you submit (which includes a reload) of the page.
Take a input type="button"instead.
function getVal1() {
var text = document.getElementById('text').value;
var par = document.getElementById('par');
par.innerHTML = text
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form>
<input type="text" id="text">
<input type="button" value="Submit" onclick="getVal1()">
</form>
<p id="par"></p>
</body>
</html>

onclick display the code entered along with database without using iframe( just like when we post a news it appears in facebook)

I am trying to display the content just like in facebook.but i dint get it.i used iframe.can some one help me with this without using iframe.i want it to get independently ..like if user1 post it must be seperated from user2 ..but i didnt get it using iframe ii just got a linebreak ..
i here by attaching two images for idea sake facebook layout
this is my outcome.it would be helpful if u solve ...Thanks in Advance..atleast the working ui would be helpful
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<body>
<div id = "midle">
<div id="posts" >
<h1>WHAT'S UP?</h1>
<tr> <form method="POST" action="tryy.php" target="iframe_a" >
<textarea name="post" rows="5" cols=110" target="iframe_a" ></textarea>
<td><input id="button" type="submit" name="submit" value="POST" ></td>
</form>
<iframe width="100%" height="590" src="tryy.php" name="iframe_a"></iframe>
</div>
</div>
</html>
You can use ajax.
(replace the iframe with a div that for this example has the id "status")
<div id="status"></div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$.get(
'tryy.php',
function(response){
$("#status").html(response);
}
);
</script>
Inserted into your example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
#status {
background:#555;
width: 100%;
height: 590px;
}
</style>
</head>
<body>
<div id="midle">
<div id="posts">
<h1>WHAT'S UP?</h1>
<tr>
<form method="POST" action="tryy.php" target="iframe_a">
<textarea name="post" id="statusBox" rows="5" cols=110 target="iframe_a " ></textarea>
<td><input id="button" type="submit" name="submit " value="POST " ></td>
</form>
<div id="status"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js "></script>
<script>
function updateStatusList(){
$.get(
'tryy.php',
function(response){
$("#status").html(response);
}
);
}
$("#button").click(function(e) {
e.preventDefault();
updateStatusList();
return false;
});
$("#statusBox").keydown(function(e) {
if(e.keyCode == 13){ // when return was pressed
updateStatusList();
}
});
</script>
</body>
</html>
PS:
Since you are new some hints:
You should use <!DOCTYPE html> instead.
Use a closing </body> tag ;)
Don't use td, tr elements without a table element (and you shouldn't actually use tables at all for layouting)

How to input user data through a text field, then display immediately below the text field?

I am new to Javascript, but basically I want to take the users text, and once they hit the button, be able to output it below the button. This is what I have so far:
<html lang="en">
<head>
<meta charset="utf-8" />
<title>title</title>
<link rel="stylesheet" href="main.css">
<script>
var message = "#";
$("#message").text(message);
</script>
</head>
<body>
<div id="wrapper">
<var id="message"></var><textarea rows="4" cols="50" placeholder="Enter their post here, exactly word for word." id="post"></textarea></var>
<button type="button">Submit</button>
</div>
</div>
</body>
</html>
$("#button").click(function(){
var text = document.getElementById("post").value;
$("#message").html(text);
});
<div id="wrapper">
<textarea rows="4" cols="50" placeholder="Enter their post here, exactly word for word." id="post"></textarea>
<button id="button" type="button">Submit</button>
</div>
<span id="message"></span>
Result: http://jsfiddle.net/YoshiMaster/1r177khr/4/
This is without jQuery.
Add an id to your button and create the empty text area with id 'textDiv' and try this.
<script type="text/javascript">
var button = document.getElementById('button_ID');
button.addEventListener('click',showText);
function showText() {
document.getElementById('textDiv').innerHTML = 'new text';
}
</script>

Categories

Resources