I'm trying to do a little practicing on my own, combining elements of Jon Duckett's JavaScript and JQuery book with those of Treehouse's JavaScript Basics track. Basically the program allows someone to type in text and see how much it would cost to make a sign with that text.
When I try to copy the text from the input element and place it next to custom sign, my input.value returns a zero. Any help would be greatly appreciated with figuring this out
var btnCalc = document.getElementById('myButton');
// Here's where I have the issue
var textInput = document.getElementById('textInput').value;
var customSign = document.getElementById('customSign');
var totalTiles = textInput.length;
var subtotal = totalTiles * 5;
var shipping = 7;
var grandTotal = subtotal + shipping;
btnCalc.addEventListener('click', Calculate);
function Calculate() {
// and here
document.getElementById('customSign').innerHTML = textInput;
document.getElementById('totalTiles').textContent = totalTiles;
document.getElementById('subtotal').textContent = subtotal;
document.getElementById('shipping').textContent = shipping;
document.getElementById('grandTotal').textContent = grandTotal;
}
h2 {
text-align: center;
}
span {
font-weight: bold;
}
div {
margin: 0 auto;
width: 400px;
overflow: auto;
}
ul {
list-style-type: none;
}
#right-col {
float: right;
}
#left-col {
float:left;
}
#input-form {
text-align: center;
}
<html>
<head>
<title>Duckett Chapter 2 Example</title>
<link href="styles.css" rel="stylesheet "type="text/css" >
</head>
<body>
<h2 id="greeting">Howdy Molly, please check your order: </h2>
<div>
<ul id="left-col">
<li><span>Custom Sign: </span> </li>
<li><span>Total Tiles: </span></li>
<li><span>Subtotal: </span></li>
<li><span>Shipping: </span></li>
<li><span>Grand Total: </span></li>
</ul>
<ul id="right-col">
<li id="customSign">Montague Hotel</li>
<li id="totalTiles">14</li>
<li id="subtotal">$70</li>
<li id="shipping">$7</li>
<li id="grandTotal">$77</li>
</ul>
<div id="input-form">
<input id="textInput" type="text">
<button id="myButton">Calculate</button>
</div>
</div>
<script src="scripts.js"></script>
</body>
</html>
Your variables have to be inside your function, otherwise their values are already empty when you call it.
var btnCalc = document.getElementById('myButton');
btnCalc.addEventListener('click', Calculate);
function Calculate() {
var textInput = document.getElementById('textInput').value;
var customSign = document.getElementById('customSign');
var totalTiles = textInput.length;
var subtotal = totalTiles * 5;
var shipping = 7;
var grandTotal = subtotal + shipping;
document.getElementById('customSign').innerHTML = textInput;
document.getElementById('totalTiles').textContent = totalTiles;
document.getElementById('subtotal').textContent = subtotal;
document.getElementById('shipping').textContent = shipping;
document.getElementById('grandTotal').textContent = grandTotal;
}
Move calculation part to the function.
var btnCalc = document.getElementById('myButton');
// Here's where I have the issue
var textInput = document.getElementById('textInput');
var customSign = document.getElementById('customSign');
btnCalc.addEventListener('click', Calculate);
function Calculate() {
var totalTiles = textInput.value.length;
var subtotal = totalTiles * 5;
var shipping = 7;
var grandTotal = subtotal + shipping;
// and here
document.getElementById('customSign').innerHTML = textInput.value;
document.getElementById('totalTiles').textContent = totalTiles;
document.getElementById('subtotal').textContent = subtotal;
document.getElementById('shipping').textContent = shipping;
document.getElementById('grandTotal').textContent = grandTotal;
}
h2 {
text-align: center;
}
span {
font-weight: bold;
}
div {
margin: 0 auto;
width: 400px;
overflow: auto;
}
ul {
list-style-type: none;
}
#right-col {
float: right;
}
#left-col {
float:left;
}
#input-form {
text-align: center;
}
<html>
<head>
<title>Duckett Chapter 2 Example</title>
<link href="styles.css" rel="stylesheet "type="text/css" >
</head>
<body>
<h2 id="greeting">Howdy Molly, please check your order: </h2>
<div>
<ul id="left-col">
<li><span>Custom Sign: </span> </li>
<li><span>Total Tiles: </span></li>
<li><span>Subtotal: </span></li>
<li><span>Shipping: </span></li>
<li><span>Grand Total: </span></li>
</ul>
<ul id="right-col">
<li id="customSign">Montague Hotel</li>
<li id="totalTiles">14</li>
<li id="subtotal">$70</li>
<li id="shipping">$7</li>
<li id="grandTotal">$77</li>
</ul>
<div id="input-form">
<input id="textInput" type="text">
<button id="myButton">Calculate</button>
</div>
</div>
<script src="scripts.js"></script>
</body>
</html>
Related
I'm trying to add an Delete button function to a drag and drop shopping cart. I have the button in place but I can not call a function that seems to work. I'm very novice.
Im not sure if were the function should appear because the list is created from a drag and drop menu
Below is the code so far - any help would be greatly appreciated
thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>HTML 5 Drag and Drop Shopping Cart</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.products1 { grid-area: products1; }
.menu1 { grid-area: menu1; }
.menu2 { grid-area: menu2; }
.menu3 { grid-area: menu3; }
.menu4 { grid-area: menu4; }
.grid-container {
display: grid;
grid-template-areas:
'products1 menu1 menu2 menu3 menu4'
;
grid-gap: 5px;
background-color: #2196F3;
padding: 5px;
}
.grid-container > div {
background-color: rgba(255, 255, 255, 0.8);
text-align: center;
padding: 20px 0;
font-size: 20px;
}
#item-container{
width: 280px;
padding: 10px;
border: 5px solid gray;
margin:20px auto;
text-align: center;
font-size: 20px;
}
ul, li{
list-style: none;
margin: 2px;
padding: 0px;
cursor: grabbing;
}
section#cart ul{
height: 600px;
overflow: auto;
background-color: #cccccc;
}
</style>
<script src="jquery-3.3.1.min.js"></script>
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var items = document.querySelectorAll("section.products ul li");
var cart = document.querySelectorAll("#cart ul")[0];
function updateCart(){
var total = 0;
var term = 48;
var rate = 7;
var amount = 15090;
var cart_items = document.querySelectorAll("#cart ul li")
for (var i = 0; i < cart_items.length; i++) {
var cart_item = cart_items[i];
var quantity = cart_item.getAttribute('data-quantity');
var price = cart_item.getAttribute('data-price');
var payment = amount*((((rate/12)/100)*((1+((rate/12)/100))**term))/(((1+((rate/12)/100))**term)-1));
var sub_total = parseFloat(quantity * parseFloat(price));
cart_item.querySelectorAll("span.sub-total")[0].innerHTML = + sub_total.toFixed(2);
total += sub_total*((((rate/12)/100)*((1+((rate/12)/100))**term))/(((1+((rate/12)/100))**term)-1));
newpayment=total+payment
}
document.querySelectorAll("#cart span.total")[0].innerHTML = total.toFixed(2);
document.querySelectorAll("#cart span.newpayment")[0].innerHTML = newpayment.toFixed(2);
}
function addCartItem(item, id) {
var clone = item.cloneNode(true);
clone.setAttribute('data-id', id);
clone.setAttribute('data-quantity', 1);
clone.removeAttribute('id');
var fragment = document.createElement('span');
fragment.setAttribute('class', 'quantity');
fragment.innerHTML = '<button id="butt" onclick="one(this);">delete item</button> $';
clone.appendChild(fragment);
fragment = document.createElement('span');
fragment.setAttribute('class', 'sub-total');
clone.appendChild(fragment);
cart.appendChild(clone);
}
function updateCartItem(item){
var quantity = item.getAttribute('data-quantity');
quantity = parseInt(quantity) + 1
item.setAttribute('data-quantity', quantity);
var span = item.querySelectorAll('span.quantity');
span[0].innerHTML = ' x ' + quantity;
}
function onDrop(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var id = event.dataTransfer.getData("Text");
var item = document.getElementById(id);
var exists = document.querySelectorAll("#cart ul li[data-id='" + id + "']");
{
addCartItem(item, id);
}
updateCart();
return false;
}
function onDragOver(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
return false;
}
addEvent(cart, 'drop', onDrop);
addEvent(cart, 'dragover', onDragOver);
function onDrag(event){
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.dropEffect = "move";
var target = event.target || event.srcElement;
var success = event.dataTransfer.setData('Text', target.id);
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
item.setAttribute("draggable", "true");
addEvent(item, 'dragstart', onDrag);
};
});
</script>
</head>
<body>
<div id="page">
<div class="grid-container">
<div class="products1">
<section id="products" class="products">
<h1></h1>
<ul>
<li id="product-1" data-price="3999.00"><div id="item-container">Product 1<br> descr<br>descr </div></li>
<li id="product-2" data-price="1895"><div id="item-container">Product 2<br> descr<br>descrip</div></li>
<li id="product-3" data-price="2.99"><span>Product 3</span></li>
<li id="product-4" data-price="3.50"><span>Product 4</span></li>
<li id="product-5" data-price="4.25"><span>Product 5</span></li>
<li id="product-6" data-price="6.75"><span>Product 6</span></li>
<li id="product-7" data-price="1.99"><span>Product 7</span></li>
</ul>
</section>
</div>
<div class="menu1">
<section id="cart" class="shopping-cart">
<h1>Preferred</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
<p> $<span class="newpayment">0.00</span></p>
</section>
</div>
<div class="menu2">
<section id="cart" class="shopping-cart">
<h1>Value</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
</section>
</div>
<div class="menu3">
<section id="cart" class="shopping-cart">
<h1>Basic</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
</section>
</div>
<div class="menu4">
<section id="cart" class="shopping-cart">
<h1>Economy</h1>
<ul>
</ul>
<p> $<span class="total">0.00</span></p>
</section>
</div>
</div>
</div>
</body>
</html>
I'm trying to make a ninja fruit style game in javascript but problems are happening. I have this if statements that compare the variable "fruit" with the index of the "fruits" array. The problem is when I "eliminate" a fruit the other if statements doenst work.
That's how the game needs to work:
1 You start the game, a random name of a fruit appears for you to click on.
2 You click in the image of the fruit and it disappears, in this click another random fruit is generated.
3 An then you finish the game, that's prety much this.
So it's kind hard to explain, but its the same logic as the ninja fruit game. And I dont know if I need to use the shift function to eliminate the fruits in the array as well.
var fruits = ['Banana', 'Apple', 'Pineapple'];
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
if (fruit == fruits[0]) {
bana.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
bana.style.display = "none";
}
}
if (fruit == fruits[1]) {
app.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
app.style.display = "none";
}
}
if (fruit == fruits[2]) {
pin.onclick = function() {
var fruit = fruits[Math.floor(Math.random() * fruits.length)];
document.getElementById("frut").innerHTML = fruit;
pin.style.display = "none";
}
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>
Right now, you're only attaching handlers to the fruit images at the top level, in your if statements - but once those statements run and the main block finishes, it doesn't get run again.
You should attach handlers to all fruit images at once in the beginning, and then in the handlers, check to see the clicked fruit was valid.
If you're assigning text to an element, assign to textContent, not innerHTML; textContent is quicker, safer, and more predictable.
const fruits = ['Banana', 'Apple', 'Pineapple'];
const getRandomFruit = () => {
const randomIndex = Math.floor(Math.random() * fruits.length);
const fruit = fruits[randomIndex];
document.getElementById("frut").textContent = fruit;
fruits.splice(randomIndex, 1);
return fruit;
};
let fruitToClickOn = getRandomFruit();
bana.onclick = function() {
if (fruitToClickOn !== 'Banana') return;
bana.style.display = "none";
fruitToClickOn = getRandomFruit();
}
app.onclick = function() {
if (fruitToClickOn !== 'Apple') return;
app.style.display = "none";
fruitToClickOn = getRandomFruit();
}
pin.onclick = function() {
if (fruitToClickOn !== 'Pineapple') return;
pin.style.display = "none";
fruitToClickOn = getRandomFruit();
}
function movFruit() {
document.getElementById("info").style.display = "table";
document.getElementById("fruitAnimation").style.display = "table";
document.getElementById("insructions").style.display = "none";
var elem = document.getElementById("fruitAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
}
}
}
#fruitAnimation {
position: relative;
display: none;
margin: 0 auto;
}
.fr {
float: left;
padding: 80px;
}
#info {
display: none;
margin: 0 auto;
}
#insructions {
display: table;
margin: 0 auto;
margin-top: 200px;
border: 1px solid black;
padding: 10px;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title>JSfruit</title>
</head>
<body>
<div id="info">
<h1>Fruit: <span id="frut"></span></h1>
</div>
<button onclick="movFruit() " style="display: table; margin: 0 auto;"><h4>Start the game</h4></button>
<div id="fruitAnimation">
<div class="fr" id="bana">
<img src="https://orig00.deviantart.net/5c87/f/2016/322/8/9/banana_pixel_art_by_fireprouf-daosk9z.png" width="60" height="60">
</div>
<div class="fr" id="app">
<img src="https://art.ngfiles.com/images/404000/404664_thexxxreaper_pixel-apple.png?f1454891997" width="60" height="60">
</div>
<div class="fr" id="pin">
<img src="https://i.pinimg.com/originals/c2/f9/e9/c2f9e9f8d332da97a836513de98f7b29.jpg" width="60" height="60">
</div>
</div>
<span id="insructions">Click in the fruits and erase them!</span>
</body>
</html>
I am trying to convert Node List to Array. I want to print the list (caption 1,...caption 5), but it prints:
[object HTMLLIElement],[object HTMLLIElement],[object HTMLLIElement],[object HTMLLIElement],[object HTMLLIElement],[object HTMLLIElement]
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Caption</title>
<style>
.captn {
position: absolute;
padding: 10px;
margin: 200px auto;
text-align: center;
font-family:serif, fantasy;
font-size:36px;
color: #009933;
text-decoration: none;
text-transform: uppercase;
list-style-type: none;
}
</style>
</head>
<body>
<div>
<ul id = "caption" class="captn"><li id = "caption0">caption 0</li><li id = "caption1">caption 1</li><li id = "caption2">caption 2</li><li id = "caption3">caption 3</li><li id = "caption4">caption 4</li><li id = "caption5">caption 5</li></ul>
</div>
<script>
var msg;
var cap = [];
var capList;
var f = document.getElementsByClassName("captn");
msg = f.item(0).childNodes;
b = f.item(0).childNodes.length;
var classAr = Array.prototype.slice.call(msg);
document.write(classAr);
</script>
</body>
</html>
Use querySelectorAll and select all elements under class captn with an id beginning with caption, then convert the node list to array usingArray.from and lastly map through the array, returning a new array containing only the textContent
var captions = Array.from(
document.querySelectorAll('.captn [id^="caption"]')
);
var captionsText = captions.map(function(caption) {
return caption.textContent;
});
document.write(captionsText);
<div>
<ul id="caption" class="captn">
<li id="caption0">caption 0</li>
<li id="caption1">caption 1</li>
<li id="caption2">caption 2</li>
<li id="caption3">caption 3</li>
<li id="caption4">caption 4</li>
<li id="caption5">caption 5</li>
</ul>
</div>
You can use Array.from().
Array.from(nodeList)
First of all I want to thank #Red Mercury that his answer greatly boosted my knowledge in JavaScript. I am new to Stack Overflow and don't know how to mark his answer green, if there is a gold mark, I would do for him. Thank you Red Mercury.
What I was trying to do is to put captions list as a sliding captions. It was easy to do with arrays in Javascript, but I was unable to convert node list into array, because nodelist did not work in loops with innerHtml. So here is the solution:
<html>
<head>
<title>Slide 3</title>
<style>
.captn {
padding-top: 550px;
text-align:center;
font-family:serif, fantasy;
font-size:36px;
color: #009933;
text-decoration: none;
text-transform: uppercase;
}
</style>
</head>
<body>
<div>
<ul id = "caption" class="captn">
<li id = "caption0">caption 0</li>
<li id = "caption1">caption 1</li>
<li id = "caption2">caption 2</li>
<li id = "caption3">caption 3</li>
<li id = "caption4">caption 4</li>
<li id = "caption5">caption 5</li>
<li id = "atim">item</li>
<li id = "caption6">caption 6</li>
</ul>
</div>
<script>
var i = 0;
var j = 0;
var intv = 1000;
var msg = "";
var cap = [];
var capList = "";
var captions = Array.from(
document.querySelectorAll('.captn [id ^= "caption"]')
);
var captionsText = captions.map(function(caption) {
return caption.textContent;
})
for (i = 0; i < captions.length; i++) {
cap[i] = captionsText[i] + "<br>";
msg = cap[i];
capList += msg.replace(/\,/g, "");
}
b = captions.length;
function swapImage() {
var elm = document.getElementById("caption");
elm.innerHTML = cap[j];
if(j < b - 1 ) {
j++;
}
else {
j = 0;
}
setTimeout("swapImage()", intv);
}
window.onload=swapImage;
</script>
</body>
</html>
I have order list in HTML :
<ol id="myList">
<li>Tea</li>
<li>Milk</li>
<li>Water</li>
</ol>
<button onclick="myFunction()">Try it</button>
And Ii write code in Javascript, and now I can add one item in this list. I have also set up limit of adding items. When I add one items, then how can I delete it?
<script>
var limit = 1
var currentAmount = 0;
function myFunction() {
//Check we haven't reached our limit.
if(currentAmount < limit){
var x = document.createElement("li");
var t = document.createTextNode("Coffee");
x.appendChild(t);
document.getElementById("myList").appendChild(x);
currentAmount++; //Increment our count
}
}
</script>
You could add remove button to every item in the list and attach onclick event to it that will call removeItem() function, check example below.
Hope this helps.
Snippet
var limit = 1
var currentAmount = 0;
function myFunction() {
//Check we haven't reached our limit.
if(currentAmount < limit){
var x = document.createElement("li");
var remove_btn = document.createElement("input");
remove_btn.setAttribute("type", "button");
remove_btn.setAttribute("value", "X");
remove_btn.setAttribute("onclick", "removeItem(this)");
x.appendChild(remove_btn);
var t = document.createTextNode("Coffee");
x.appendChild(t);
document.getElementById("myList").appendChild(x);
currentAmount++; //Increment our count
}
}
function removeItem() {
event.target.parentNode.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="myList">
<li><button onclick="removeItem(this)">X</button> Tea</li>
<li><button onclick="removeItem(this)">X</button> Milk</li>
<li><button onclick="removeItem(this)">X</button> Water</li>
</ol>
<button onclick="myFunction()">Try it</button>
Well, it depends which element you want to remove, but for example, to remove the last element, add this button:
<button onClick="removeItem();">Now try this</button>
and this script:
function removeItem() {
document.getElementById("myList").lastChild.remove();
}
Got carried away, it removes items as OP requested and it:
Generates the delete button for every list item.
Added delete buttons for the old list items.
Added a text input so the user can input the list items.
Added an eventListener to the list in order to handle which button was clicked and save memory having one eventListener instead of one for each button.
Snippet
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Shopping List</title>
<style>
#inp1 {
margin: 10px 15px;
width: 25ex;
}
.item {
max-width: 30ex;
position: relative;
}
.del {
line-height: 1;
width: 7ex;
margin: 0 20px;
padding: 0 3px;
position: absolute;
right: -10px;
}
.del:before {
content: 'Delete';
font: inherit;
}
</style>
</head>
<body>
<h2>Shopping List</h2>
<ol id="list">
<li class="item">Tea
<button class="del"></button>
</li>
<li class="item">Milk
<button class="del"></button>
</li>
<li class="item">Water
<button class="del"></button>
</li>
</ol>
<input id="inp1" name="inp1" placeholder="Grocery Item" />
<button onclick="list(inp1.value)">Add</button>
<script>
var limit = 6
var currentAmount = 3;
var ol = document.getElementById("list");
function list(item) {
//Check we haven't reached our limit.
if (currentAmount < limit) {
var li = document.createElement("li");
var str = document.createTextNode(item);
var btn = document.createElement('button');
li.appendChild(str);
li.appendChild(btn);
li.classList.add('item');
btn.classList.add('del');
ol.appendChild(li);
currentAmount++; //Increment our count
}
return false;
}
ol.addEventListener('click', function(event) {
if (event.target != event.curentTarget) {
var tgt = event.target;
var li = tgt.parentElement;
ol.removeChild(li);
currentAmount--;
}
event.stopPropagation();
}, false);
</script>
</body>
</html>
My code atm looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
}
init();
</script>
</body>
</html>
So what I want, is for the remove-button to remove the divs that im creating. Ive been googling around and have tried alot of different codes, cant seem to get it to work..
In your specific situation, you have two basic choices:
Just set innerHTML on the element to "":
myFigures.innerHTML = "";
It's slower than some alternatives, but you're not doing this in a tight loop, and it's easy.
Use a loop with removeChild:
while (myFigures.firstChild) {
myFigures.removeChild(myFigures.firstChild);
}
See this other SO answer for information comparing the two techniques.
Here's that first option in context:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
myFigures.innerHTML = "";
}
init();
</script>
</body>
</html>
Like T.J. Crowder said,
myFigures.innerHTML = "";
would work. However, that assumes that myFigures is empty when your DOM is initially loaded. If that is NOT the case, you need to add a class to the div when you create it.
AddDiv function:
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div class='AddedDiv'></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
To remove them:
$(".AddedDiv").each(function(){
$(this).parentNode.removeChild($(this));
});