Push value to array onclick and loop to add array values. Javascript - javascript

So i am pretty new at this and want to be able to add a dollar to the "deposit" text box every time I click the button. I'm going to have to do this with a quarter, dime, and nickel, button as well. This is what I have so far.
<input type="button" value="Dollar" id="dollar" />
$<input type="text" id="deposit" />
And the javascript is:
var $ = function (id) { return document.getElementById(id); }
var item = [];
var total = 0;
for (i=0; i < item.length; i++){
total += item[i];
$("deposit").value = total;
}
$("dollar").onclick = item.push(1);
Whatever help you can give is much appreciated!

Don't you mean
Live Demo
var $ = function (id) { return document.getElementById(id); }
var add = function(fld,val) {
return (parseFloat(fld.value)+val).toFixed(2);
}
window.onload=function() {
$("dollar").onclick=function() {
$("deposit").value = add($("deposit"),1);
}
$("dime").onclick=function() {
$("deposit").value = add($("deposit"),.1);
}
$("nickel").onclick=function() {
$("deposit").value = add($("deposit"),.05);
}
$("refund").onclick = function() {
$("deposit").value = "0.00";
}
}

Try this:
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#1.9.1" data-semver="1.9.1" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="Dollar" id="dollar" />
$ <input type="text" id="deposit" />
</body>
</html>
JavaScript:
$(function() {
var item = [];
$("#dollar").click(function() {
item.push(1);
var total = 0;
for (var i = 0; i < item.length; i++) {
total += item[i];
$("#deposit").val(total);
}
});
});
Plunker example

Related

Using PokeAPI to fetch data. Can't figure out why span element is not updating

So I'm using the PokeAPI to fetch the name of a Pokemon, then shuffling that name, and the user is supposed to guess what it is in the input. If they don't know then they can click the next button and it reshuffles a new mon. If they guess right they can press the same next button for a new mon. Each time they guess right the score increases by 1. That's working but I cant figure out why the out of/total games span isn't updating as well. Please excuse my terrible attempt at JS I'm very new if you can help me make my code look better that would be great.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="style.css" />
<title>Who's that Pkmn?</title>
</head>
<body>
<header>
<h1>Who's that Pokemon?!</h1>
</header>
<div id="jumble">?????</div>
<div class="container">
<input id="guess" type="text" placeholder="enter pkmn name" />
<button id="submit" class="btn" type="submit">go</button>
<button id="next" class="btn">next</button>
<p id="msg">unshuffle the letters</p>
</div>
<div id="scorekeepers">
<p>Score: <span id="score">0</span>
out of: <span id="gamesPlayed">0</span></p>
</div>
<script src="script.js"></script>
</body>
</html>
let jumbledName = document.querySelector("#jumble");
let guessInput = document.querySelector('#guess')
let submitButton = document.querySelector('#submit')
let nextButton=document.querySelector('#next')
let messageDisplay = document.querySelector('#msg')
let score = document.querySelector('#score')
let gamesPlayed = document.querySelector('#gamesPlayed')
score = 0;
gamesPlayed = 0;
let getPokemonName = function() {
fetch(`https://pokeapi.co/api/v2/pokemon/${Math.floor(Math.random()*151+1)}/`)
.then(function(response) {
return response.json();
})
.then(function(data) {
const pokeName = data.name;
const pokeNameJumbled = pokeName.shuffle();
displayInfomation(pokeName, pokeNameJumbled);
});
};
getPokemonName();
guessInput.value=''
// pokeNameJumbled=''
const displayInfomation = function(name, jumbledName) {
pokeName = name;
pokeNameJumbled = jumbledName;
jumble.textContent = jumbledName;
};
const displayMessage = function(message) {
document.querySelector("#msg").textContent = message;
};
const checkName = function () {
document.querySelector("#guess").textContent = guessInput;
const guess = document.querySelector("#guess").value.toLowerCase();
if (!guess) {
displayMessage("No guess entered!");
} else if (guess === pokeName) {
displayMessage(`Thats correct! It's ${pokeName}!`)
score++
document.querySelector("#score").textContent = score;
guessInput.value=''
} else if (guess != pokeName) {
displayMessage(`Wrong!`);
document.querySelector("#gamesPlayed").textContent = gamesPlayed;
}
};
submitButton.addEventListener('click', checkName)
nextButton.addEventListener('click',getPokemonName)
String.prototype.shuffle = function() {
var a = this.split(""),
n = a.length;
for (var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("");
};

Sorting data in a stored array

Below is my code. I need to sort the array after the user input but can't figure out how to make that happen. I have tried several different things but nothing has worked including data.sort() and data.sort(function(a,b) { return a - b; }); but neither seems to be working. Any help would be appreciated!
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> Input integers into the array and then search the array to see if your input is present!</h1>
<p id="data">[]</p>
<input id="inputNumber" value="0" /> <button id="pushBtn" onclick="push()">PUSH</button>
<input id="findNumber" value="0" /> <button id="pushBtn" onclick="find()">FIND</button>
<script>
var data = [];
function push(e) {
for (var i = 0; i < 5; i++) {
data.push(prompt('enter integer ' + (i + 1)));
}
alert('Full array: ' + data.join(', '));
var toAdd = document.getElementById("inputNumber").value;
data.push(toAdd);
refresh();
}
function find(e) {
var toFind = document.getElementById("findNumber").value;
for (var i = 0; i < data.length; i++) {
if (data[i] == toFind) return alert("found at " + i);
}
return alert("That number was not found");
}
function refresh() {
document.getElementById("data").innerHTML = data;
}
</script>
</body>
</html>

Display elemens of 2 arrays in <li>

And thanks in advance for looking into this, I am trying to show elements of 2 arrays in html (li) tags. This should be the format echoed out:
array1; array2
c201;100
c202;0
c450;320
......
The elements that will be pushed into the array are coming from input fields. I have created the following code and I get to see the correct format but when I copy and paste the values above, it loses the format and instead of having two columns, it pastes elements of array2 just below the elements of array1:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script>
var array_accounts = [];
var array_credits = [];
var x = 0;
var i = 0;
var z = 0;
function spara(){
var accounts_code_str = document.getElementById('accounts').value;
var accounts_code_comma = accounts_code_str.split(' ');
var accounts_code_comma = accounts_code_comma.join(';<br>');
array_accounts.push(accounts_code_comma);
console.log(array_accounts);
var iz_credits_str = document.getElementById('credits').value;
var iz_credits_comma = iz_credits_str.split(" ");
//var iz_credits_comma = iz_credits_comma.join('<br> ');
for(var z=0; z<iz_credits_comma.length; z++){
if(iz_credits_comma[z] < 0){
iz_credits_comma[z] = 0;
}
}
var iz_credits_comma = iz_credits_comma.join('<br> ');
array_credits.push(iz_credits_comma);
showAccounts();
showCredits();
}
</script>
</head>
<body>
<h1>Accounts and IZ credits</h1>
<div id="form">
<form>
<label>Insertar Accounts codes</label>
<input type="text" name="accounts" id="accounts" />
<label>Insertar Iz credits</label>
<input type="text" name="credits" id="credits" />
<input type ="button" onclick="spara()" value="Process data" />
</form>
</div>
<div id="codes" style="float:left">
<script>
function showAccounts(){
for (var x=0;x<array_accounts.length;x++){
document.write('<div style="float:left;">'+array_accounts[x]+';</div>');
}
}
</script>
</div>
<div id="credits" style="float:left">
<script>
function showCredits(){
for (var i=0;i<array_credits.length;i++){
document.write('<div style="float:left;">'+array_credits[i]+'<br></div>');
}
}
</script>
</div>
</body>
</html>
Many thanks in advance for your help!
Hope this helps!
<script>
var array_accounts = [];
var array_credits = [];
var x = 0;
var i = 0;
var z = 0;
function spara(){
var accounts_code_str = document.getElementById('accounts').value;
array_accounts = accounts_code_str.split(' ');
console.log(array_accounts);
var iz_credits_str = document.getElementById('credits').value;
var iz_credits_comma = iz_credits_str.split(" ");
array_credits=iz_credits_comma;
//var iz_credits_comma = iz_credits_comma.join('<br> ');
for(var z=0; z<iz_credits_comma.length; z++){
if(iz_credits_comma[z] < 0){
iz_credits_comma[z] = 0;
}
}
showAccounts();
}
function showAccounts(){
var ol = document.createElement("OL");
for (var x=0;x<array_accounts.length;x++){
var li = document.createElement("LI");
var textnode = document.createTextNode(array_accounts[x]+';'+array_credits[x]);
li.appendChild(textnode);
ol.appendChild(li)
}
document.getElementById("codes").appendChild(ol);
}
</script>
Modify the two javascript functions and that should do the trick! Thanks.

How to display a number below each dynamically created images?

I want to display a particular image as many times as the number given by user.This part is accomplished. But i want to display a number below each image. For example if user input is 4, there should be 4 images with '1' below 1st image '2' below second. The image must also be clickable.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag()">Try it</button>
<div id="demo">
<script>
function imag(c,x) {
var x = document.getElementById("myNumber").value;
var c="<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr.join("&nbsp&nbsp");
}
}
</script>
</body>
</html>
var imageSrc = "http://fc08.deviantart.net/fs71/f/2010/148/1/9/20x20_PNG_Icons_DOMO_by_JMcIvor.png";
function imag(c,x) {
var x = document.getElementById("myNumber").value;
var demo = document.getElementById("demo");
var container = document.createElement("div");
container.setAttribute("class", "container");
for(var i=0; i<x; i++) {
var image = document.createElement("img");
image.setAttribute("class", "image");
image.setAttribute("src", imageSrc);
container.appendChild(image);
var text = document.createElement("div");
text.innerHTML = i+1;
container.appendChild(text);
demo.appendChild(container);
}
}
#demo {
}
.container {
}
.image {
}
.text {
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag()">Try it</button>
<div id="demo"></div>
</body>
</html>
I just use another image url to test the code, replace it with your one. I hope this helps.
You already have the number you're looking for in your loop. So you can simply add it to your array like this.
JS:
function imag() {
var x = document.getElementById("myNumber").value;
var c = "<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
var arr = [];
for (var i = 0; i < x; i++) {
arr.push("<div class='image'>" + c + "<br />" + (i+1) + "</div>");
}
document.getElementById("demo").innerHTML = arr.join("&nbsp&nbsp");
}
CSS:
div.image {
display: inline-block;
}

slideUp() all the elements but not the selected ones

All I want to do is:
there are 7 numbers and 7 divs, they are linked to each other (nr 0 it's in a relationship with div 0)
when one of the numbers is clicked, it should collapse all the other divs which are not selected
it can be selected more at one time
To sum up, basically, the page has some labels with numbers and 7 divs which are all displayed by default (the divs), but when one or more of them are chosen by clicking on the numbers, the page should display only the chosen divs.
This is what I've been trying to do:
for(var i = 0; i <= 6; i++) {
if(i != (floors[i])) {
$("#lvl" + floors[i]).slideUp();
}
}
More code:
http://jsfiddle.net/LSjg4/
Try
var floors = [];
var $lvls = $('.lvl'), $nrs = $(".nr");
$nrs.click(function () {
var $nr = $(this), index = $nrs.index($nr), $lvl = $lvls.eq(index);
$lvl.add($nr).toggleClass('active');
if($nr.hasClass('active')){
$lvls.not('.active').slideUp();
$lvl.slideDown();
$nr.css("background-color", "#1b7664");
$nr.css("border-color", "#236959");
floors.push(($nr).text());
} else {
$nr.css("background-color", "#02c099");
$nr.css("border-color", "#13a480");
if($nrs.filter('.active').length == 0){
$lvls.slideDown();
} else {
$lvls.not('.active').slideUp();
}
var text = $nr.text();
floors.splice($.inArray(text, floors), 1);
}
console.log('floors', JSON.stringify(floors))
});
Demo: Fiddle
I corrected a few things in your code. Here is the below working code and link to it in jsfiddle.
There was a data type mismatch(comparing string and int). When matching whether it exists in floors array, the code was checking floors[i] only whereas the i can be any position in floors.
var floors = [];
$(".nr").click(function () {
var state = $(this).data('state');
state = !state;
if (state) {
$(this).css("background-color", "#1b7664");
$(this).css("border-color", "#236959");
floors.push(parseInt($(this).text()));
console.log(floors);
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
} else {
$(this).css("background-color", "#02c099");
$(this).css("border-color", "#13a480");
for (var i = 0; i < floors.length; i++) {
if (floors[i] == parseInt($(this).text()))
floors.splice(i, 1);
}
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
}
$(this).data('state', state);
});
Demo Here: http://jsfiddle.net/bFe9T/
I believe this is what you're looking for:
$(".nr").click(function () {
$(this).toggleClass('selected');
$('.nr').each(function(){
var $target = $('#lvl'+$(this).text());
if($(this).is('.selected'))
$target.slideDown();
else
$target.slideUp();
});
});
Note that instead of changing the CSS properties I set up a class for the selected elements
Demo fiddle
Try this
$(".nr").click(function () {
//alert($(this).attr("data-select"));
if($(this).attr("data-select") === "1") {
$(this).attr("data-select","0");
} else {
$(this).attr("data-select","1");
}
$(".nr").each(function(){
if($(this).attr("data-select") === "1") {
var id = $(this).text();
$("div#lvl"+id).slideDown();
} else {
var id1 = $(this).text();
$("div#lvl"+id1).slideUp();
}
});
});
FIDDLE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideUp demo</title>
<style>
.norm { background:#cccccc; margin:3px; width:80px;height:40px; float:left;color:#000000 }
.faded { background:#ffffff; margin:3px; width:80px;height:40px; float:left;color:#ffffff }
.btn{width:80px;}
</style>
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
</head>
<body>
<button class="btn" onClick="show(1)">1</button>
<button class="btn" onClick="show(2)">2</button>
<button class="btn" onClick="show(3)">3</button>
<button class="btn" onClick="show(4)">4</button>
<button class="btn" onClick="reset()">Reset</button>
<div class="norm" id="slide1">1</div>
<div class="norm" id="slide2">2</div>
<div class="norm" id="slide3">3</div>
<div class="norm" id="slide4">4</div>
<div></div>
<script>
var save = new Array();
function show(indx){
if($.inArray(indx, save)==-1){
save.push(indx);
for(var i=0;i<5;i++){
if($.inArray(i, save)==-1){
$('#slide'+i).attr('class','faded');
}
else{
$('#slide'+i).attr('class','norm');
}
}
}
}
function reset(){
save = new Array();
for(var i=0;i<5;i++){
$('#slide'+i).attr('class','norm');
}
}
</script>
</body>
</html>

Categories

Resources