let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
for (let i = 0; i < tasks.length; i++) {
const p = document.createElement("p");
p.innerText += tasks[i]
document.body.append(p)
console.log(tasks)
}
}
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<p id="t"></p>
</body>
</html>
Basically i have this problem when i hit my add button second time it add again the first element from the array butt how do i manage to show only the last element without the first one in the next p elements when i hit add button
If you need list of p
let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
const instance = document.getElementById("t")
instance.innerHTML = '';
for (let i = 0; i < tasks.length; i++) {
const p = document.createElement("p");
p.innerText += tasks[i];
instance.appendChild(p);
}
}
If I understand your need correctly, you do not want to "repeat" displaying "task" entered previously (which will result in displaying previous input tasks multiple times) when you perform entering new task(s).
In that case, please clear the element "t" before you update it.
So the HTML is
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="enter the task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<div id="t"></div>
</body>
</html>
and the JS (motor.js) is
let tasks = []
function addV(){
if (document.getElementById("bara").value !=""){
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
var tempstring=""
for(let i = 0;i<tasks.length;i++){
tempstring=tempstring +"<br>"+ tasks[i];
//const p = document.createElement("p");
// p.innerText += tasks[i]
// document.body.append(p)
}
document.getElementById("t").innerHTML=tempstring;
document.getElementById("bara").value="";
}
}
Your DOM p tag was inside the loop thus out of scope. I also created a new taskArray to hold the new tasks. This can be seen in the console log and the innerHTML is now displaying each new task just the one time.
let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
let taskArray = [];
const p = document.createElement("p");
for (let i = 0; i < tasks.length; i++) {
p.innerText = tasks[i]
document.body.append(p)
taskArray.push(tasks[i]);
}
console.log(taskArray);
}
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<p id="t"></p>
</body>
</html>
the goal is to hide a form, do some stuff and unhide the form again. For example with this code for a progress bar I thought to do the following but the hiding/unhiding doesn't work. I'm probably overseeing something obvious.
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;
function start(max) {
show_div();
button = document.getElementById("button");
count = 0;
countmax = max;
progressbar = document.getElementById("bar");
progressbar.max = countmax;
timerID = setInterval(function(){update()},10);
show_div();
}//end function
function update() {
button.innerHTML = "Counting to " + countmax;
count = count + 100;
progressbar.value = count;
if (count >= countmax) {
clearInterval(timerID);
button.innerHTML = "Ready";
progressbar.value = 0;
}//end if
}//end function
function show_div() {
var x = document.getElementById("do_you_see_me?");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}//end function
</script>
</head>
<body>
<div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
<button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
<br>
<progress id="bar" value="0"></progress>
</p>
</body>
</html>
you can hide and unhide it. the problem with your code is when you trigger ready buton it will hide and then unhide the code automatically. this is becuase setInterval() function is asynchronious function. then you need call show_div() function inside the setInterval().
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;
function start(max) {
hide_div();
button = document.getElementById("button");
count = 0;
countmax = max;
progressbar = document.getElementById("bar");
progressbar.max = countmax;
timerID = setInterval(function()
{
update()
if(count>=countmax)
{
show_div();
}
},10);
}//end function
function update() {
button.innerHTML = "Counting to " + countmax;
count = count + 100;
progressbar.value = count;
if (count >= countmax) {
clearInterval(timerID);
button.innerHTML = "Ready";
progressbar.value = 0;
}//end if
}//end function
function show_div() {
document.getElementById("do_you_see_me?").style.display="block";
}//end function
function hide_div()
{
document.getElementById("do_you_see_me?").style.display="none";
}
</script>
</head>
<body>
<div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
<button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
<br>
<progress id="bar" value="0"></progress>
</p>
</body>
</html>
i hope this will fix your problem.
I'm learning java script and I'm currently working with testing in javiscritp, I've done this code that you can look at, but I don't know how to reverse now the order of these cubes to be 2 up and 1 down (see what I want in the picture) I know I need to change something for loops but I fail in any way to get what I want.
let Tabela = (function () {
const dajRed = function (tabela) {
let red = document.createElement("tr");
tabela.appendChild(red);
return red;
}
const dajCeliju = function (red, prikazi) {
let celija = document.createElement("td");
if (!prikazi) celija.style = "display:none;";
red.appendChild(celija)
return celija;
}
const crtaj = function (x, y) {
const body = document.getElementsByTagName("body")[0];
let tabelaEl = document.createElement("table");
body.appendChild(tabelaEl);
for (let i = 0; i < y; i++) {
let red = dajRed(tabelaEl);
for (let j = 0; j < x; j++) {
dajCeliju(red, j < i);
}
}
}
return {
crtaj: crtaj
}
}());
//table.crtaj(3,3)
//i=0 ⍉⍉⍉
//i=1 ⎕⍉⍉
//i=2 ⎕⎕⍉
//Tabela.crtaj(8, 8);
let assert = chai.assert;
describe('Tabela', function() {
describe('crtaj()', function() {
it('should draw 3 rows when parameter are 2,3', function() {
Tabela.crtaj(2,3);
let tabele = document.getElementsByTagName("table");
let tabela = tabele[tabele.length-1]
let redovi = tabela.getElementsByTagName("tr");
assert.equal(redovi.length, 3,"Broj redova treba biti 3");
});
it('should draw 2 columns in row 2 when parameter are 2,3', function() {
Tabela.crtaj(2,3);
let tabele = document.getElementsByTagName("table");
let tabela = tabele[tabele.length-1]
let redovi = tabela.getElementsByTagName("tr");
let kolone = redovi[2].getElementsByTagName("td");
let brojPrikazanih = 0;
for(let i=0;i<kolone.length;i++){
let stil = window.getComputedStyle(kolone[i])
if(stil.display!=='none') brojPrikazanih++;
}
assert.equal(brojPrikazanih, 2,"Broj kolona treba biti 2");
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Mocha Tests</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
<style>
td{
border: 1px solid black;
height: 20px;
width: 20px;
}
</style>
</head>
<body>
<div id="ispis"></div>
<div id="mocha"></div>
<script src="https://unpkg.com/chai/chai.js"></script>
<script src="https://unpkg.com/mocha/mocha.js"></script>
<script class="mocha-init">
mocha.setup('bdd');
mocha.checkLeaks();
</script>
<script src="tabela.js"></script>
<script src="test.js"></script>
<script class="mocha-exec">
mocha.run();
</script>
</body>
</html>
Invert the check in dajCeliju:
if (prikazi) celija.style = "display:none;";
OR second option - change the params:
dajCeliju(red, j >= i);
Is this what you need?
I have just created random number. My problems is how to get value random in id and how to set price changes automatically every 5 seconds and the fluctuation amplitude less than +/- 5% compared to the current, I don't know use the setinterval function everybody help me
My code Random Price :
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
It took me a while to work around the recursion issues I was running into, before I came up with a better solution.
//<![CDATA[
// external.js
function RandNumMaker(min, max, withinPercent, secondsInterval, decimalPlaces){
this.withinPercent = withinPercent || 5;
this.secondsInterval = secondsInterval || 5;
this.decimalPlaces;
if(decimalPlaces){
this.decimalPlaces = decimalPlaces;
}
var t = this, ia = [];
function rb(mn, mx){
return mx-Math.random()*(mx-mn);
}
var pn = rb(min, max);
function rn(){
var p = 1;
if(Math.floor(Math.random()*2) === 1)p = -1
return p*(Math.floor(Math.random()*t.withinPercent)+1)/100*pn;
}
function rf(){
var r, d = t.decimalPlaces;
pn += rn();
if(pn < min || pn > max){
return rf();
}
r = pn;
if(d)r = (Math.floor(Math.round(Math.pow(10, d+1)*r)/10)/Math.pow(10, d)).toFixed(d);
return r;
}
this.setDiv = function(div){
div.innerHTML = rf(); ia = [];
var iv = setInterval(function(){
div.innerHTML = rf();
}, this.secondsInterval*1000);
ia.push(iv);
return this;
}
this.stop = function(){
for(var i=0,l=ia.length; i<l; i++){
if(ia[i]){
clearInterval(ia[i]);
}
}
ia = [];
return this;
}
}
var doc, bod, C, E, N, old = onload; // for use on other loads
onload = function(){
if(old)old();
doc = document; bod = doc.body;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
N = function(className, inElement){
var ii = inElement || doc;
var cN = ii.getElementsByClassName(className);
if(cN){
return cN;
}
var tn = ii.getElementsByTagName('*');
for(var i=0,e,a=[],l=tn.length; i<l; i++){
e = tn[i];
if(e.className && e.className === className)a.push(e);
}
return a;
}
var sr = new RandNumMaker(0, 99.99), sl = N('slow');
var fr = new RandNumMaker(0, 99.99), fs = N('fast');
sr.decimalPlaces = 2;
fr.secondsInterval = 0.1; fr.withinPercent = 5;
for(var i=0,l=sl.length; i<l; i++){
sr.setDiv(sl[i]);
}
for(var i=0,l=fs.length; i<l; i++){
fr.setDiv(fs[i]);
}
}
//]]>
/* extrnal.js */
html,body{
padding:0; margin:0;
}
body{
background:#000; overflow-y:scroll;
}
.main{
width:940px; background:#fff; padding:20px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>test</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<hr />
<div class='fast'></div>
<div class='fast'></div>
<div class='fast'></div>
<div class='fast'></div>
</div>
</body>
</html>
Should work now!
After you create a new RandNumMaker(min, max) then you can set randomNumMarkerInstance.decimalPlaces, randomNumMakerInstance.withinPercent and randomNumMakerInstance.secondsInterval using simple assignment. randomNumMakerInstance.setDiv(div) starts it. randomNumMakerInstance.stop() stops it.
I think you can understand this code.
I tried to keep your code.
The key is to use setInterval function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<script>
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
function assignData(){
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
setInterval(assignData, 5000); //every 5 seconds
}
</script>
<body onload="assignData()">
<h2 id="price1"></h2>
<h2 id="price2"></h2>
<h2 id="price3"></h2>
<h2 id="price4"></h2>
<h2 id="price5"></h2>
<h2 id="price6"></h2>
<h2 id="price7"></h2>
</body>
</html>
My interpretation of your question: all elements to start with a random value between 0 and 99.99, and then every five seconds one randomly selected element is to be updated, changing its value by a random amount within 5% of its current value. (If you want to update every element every five seconds then change the random selection to be a loop instead.)
For simplicity in the demo snippet (click "Run code snippet" to see it work), I've used a group of <li> elements which I select with .querySelectorAll("li"), but if you really want to do it using element IDs you could say .querySelectorAll("#price1,#price2,#price3,#price4,#price5,#price6,#price7").
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
}
// get list of elements:
var elements = document.querySelectorAll("li");
// populate all elements initially:
[].forEach.call(elements, function(el) {
el.innerHTML = generateRandomNumber(0,99.99);
});
// update an element at random every second:
setInterval(function update() {
var element = elements[Math.floor(Math.random() * elements.length)];
var currentVal = +element.innerHTML;
element.innerHTML = generateRandomNumber(currentVal * 0.95, currentVal * 1.05);
}, 1000);
<ul>
<li></li><li></li><li></li><li></li><li></li><li></li><li></li>
</ul>
Note that five second intervals seemed too slow for a demo, so I've used one second (1000ms) here.
Further reading:
.querySelectorAll()
Array .forEach() method
Function.prorotype.call()
Math.floor()
unary plus operator
Hope this will help.
<body>
<p id="price1"></p>
<p id="price2"></p>
<p id="price3"></p>
<p id="price4"></p>
<p id="price5"></p>
<p id="price6"></p>
<p id="price7"></p>
</body>
<script>
//set initial random number for the elements
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
//set random number to elements with fluctuation +/- 5%
setRandomToElements()
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
function setRandomToElements(){
//get current prices
var currentPrice1 = parseInt(document.getElementById('price1').innerHTML);
var currentPrice2 = parseInt(document.getElementById('price2').innerHTML);
var currentPrice3 = parseInt(document.getElementById('price3').innerHTML);
var currentPrice4 = parseInt(document.getElementById('price4').innerHTML);
var currentPrice5 = parseInt(document.getElementById('price5').innerHTML);
var currentPrice6 = parseInt(document.getElementById('price6').innerHTML);
var currentPrice7 = parseInt(document.getElementById('price7').innerHTML);
var fluctuation = 0.05;//5%
//random new numbers +/-5% current price
document.getElementById('price1').innerHTML = generateRandomNumber(currentPrice1-(currentPrice1*fluctuation), currentPrice1+(currentPrice1*fluctuation));
document.getElementById('price2').innerHTML = generateRandomNumber(currentPrice2-(currentPrice2*fluctuation), currentPrice2+(currentPrice2*fluctuation));
document.getElementById('price3').innerHTML = generateRandomNumber(currentPrice3-(currentPrice3*fluctuation), currentPrice3+(currentPrice3*fluctuation));
document.getElementById('price4').innerHTML = generateRandomNumber(currentPrice4-(currentPrice4*fluctuation), currentPrice4+(currentPrice4*fluctuation));
document.getElementById('price5').innerHTML = generateRandomNumber(currentPrice5-(currentPrice5*fluctuation), currentPrice5+(currentPrice5*fluctuation));
document.getElementById('price6').innerHTML = generateRandomNumber(currentPrice6-(currentPrice6*fluctuation), currentPrice6+(currentPrice6*fluctuation));
document.getElementById('price7').innerHTML = generateRandomNumber(currentPrice7-(currentPrice7*fluctuation), currentPrice7+(currentPrice7*fluctuation));
setInterval(setRandomToElements, 5000);
}
</script>
Fiddle
New to coding having issues with my JS code. It was working for a the last few days and then im not sure what happened now its giving me an error on line (17) todos.push(task); Error says "todos.push() is not a funsction." Any help would be greatly appreciated.
function get_todos()
{
var todos = new Array;
var todos_str = localStorage.getItem('todo');
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
function add()
{
var task = document.getElementById('task').value;
var todos = get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function remove()
{
var id = this.getAttribute('id');
var todos = get_todos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function show()
{
var todos = get_todos();
var html = '<table>';
for(var i=0; i<todos.length; i++)
{
html += '<br><tr><strong>'+
'<input type="image" src="/Pictures/remove.png" class="remove" id="' + i +
'"></input>' + todos[i] + '</strong><input type="checkbox" name="cBox" store="checkbox1" id="isDone"><label for="cBox"</label></tr><br>';
};
html += '</table>';
document.getElementById('todos').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++)
{
buttons[i].addEventListener('click', remove);
};
}
document.getElementById('add').addEventListener('click', add);
show();
My HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
</head>
<body>
<img id="mainImg" src="\Pictures\mytodolist.jpg"
<form>
<div>
<img id="taskImg" src="\Pictures\tasks.jpg"
<br>
<br>
<input id="add" type="image" width='150' heigth='80' src="\Pictures\addButton.png" ></input>
<br>
<input id="task">
</div>
<div id="todos"></div>
<script src= "ToDo.js"></script>
<link rel= "stylesheet" type= "text/css" href="todoStyle.css"/>
</body>
</html>
Seems to be working fine here: http://codepen.io/ilanus/pen/xOXJXW you declare an Array in your get_todos() function return it, then add items to it todos.push(task);