when i try to add a specific value with value="444" on the usd input it does not convert to the other value eth it's only working when i enter manually the amount. how can i convert when it's value already specified in the code
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" name="eth" class="currencyField" placeholder="ETH">
<div class="arrow" style="margin: 0 10px";>=</div>
<input type="number" name="usd" value="444" class="currencyField" value="" placeholder="USD">
</div><span id="price"></span>
<script type="text/javascript">
$(".currencyField").keyup(function(){ //input[name='calc']
let convFrom;
if($(this).prop("name") == "eth") {
convFrom = "eth";
convTo = "usd";
}
else {
convFrom = "usd";
convTo = "eth";
}
$.getJSON( "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=ethereum",
function( data) {
var origAmount = parseFloat($("input[name='" + convFrom + "']").val());
var exchangeRate = parseInt(data[0].current_price);
let amount;
if(convFrom == "eth")
amount = parseFloat(origAmount * exchangeRate);
else
amount = parseFloat(origAmount/ exchangeRate);
$("input[name='" + convTo + "']").val(amount.toFixed(2));
price.innerHTML = amount
});
});
</script>
</body>
</html>
Try this
<script type="text/javascript">
$(document).ready(function () {
function getJSONData() {
if ($(this).prop("name") == "eth") {
convFrom = "eth";
convTo = "usd";
} else {
convFrom = "usd";
convTo = "eth";
}
$.getJSON("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=ethereum", function (data) {
var origAmount = parseFloat($("input[name='" + convFrom + "']").val());
var exchangeRate = parseInt(data[0].current_price);
let amount;
if (convFrom == "eth") amount = parseFloat(origAmount * exchangeRate);
else amount = parseFloat(origAmount / exchangeRate);
$("input[name='" + convTo + "']").val(amount.toFixed(2));
price.innerHTML = amount;
});
}
getJSONData();
$(".currencyField").keyup(function () {
//input[name='calc']
getJSONData();
});
});
</script>
First of all, you must change the function out of keyup, because we don't do it. The function works when you enter value.
Related
I am not so good at JS, I have been battling with this code that should let me convert Ethereum to a selected Currency as i type value into input field, it does nothing and when i debug it, it seems to keep returning NaN with the error:
The specified value "NaN" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?
Below is my code, your help is appreciated greatly.
code:
$(".currencyField").keyup(function(){ //input[name='calc']
let convFrom;
if($(this).prop("name") == "eth") {
convFrom = "eth";
convTo = "usd";
}
else {
convFrom = "usd";
convTo = "eth";
}
$.getJSON( "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=ethereum",
function( data) {
var origAmount = parseFloat($("input[name='" + convFrom + "']").val());
var exchangeRate = parseInt(data.current_price);
let amount;
if(convFrom == "eth")
amount = parseFloat(origAmount * exchangeRate);
else
amount = parseFloat(origAmount/ exchangeRate);
$("input[name='" + convTo + "']").val(amount.toFixed(2));
price.innerHTML = amount
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" name="eth" class="currencyField" placeholder="ETH">
<div class="arrow" style="margin: 0 10px";>=</div>
<input type="number" name="usd" class="currencyField" placeholder="USD">
</div><span id="price"></span>
If you look at the response for the api, it looks like it returns an array. So to access the the current_price you would need to reference the array's index:
var exchangeRate = parseInt(data[0].current_price);
Full code below:
$(".currencyField").keyup(function(){ //input[name='calc']
let convFrom;
if($(this).prop("name") == "eth") {
convFrom = "eth";
convTo = "usd";
}
else {
convFrom = "usd";
convTo = "eth";
}
$.getJSON( "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=ethereum",
function( data) {
var origAmount = parseFloat($("input[name='" + convFrom + "']").val());
var exchangeRate = parseInt(data[0].current_price);
let amount;
if(convFrom == "eth")
amount = parseFloat(origAmount * exchangeRate);
else
amount = parseFloat(origAmount/ exchangeRate);
$("input[name='" + convTo + "']").val(amount.toFixed(2));
price.innerHTML = amount
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" name="eth" class="currencyField" placeholder="ETH">
<div class="arrow" style="margin: 0 10px";>=</div>
<input type="number" name="usd" class="currencyField" placeholder="USD">
</div><span id="price"></span>
More Details:
Program should receive a number and continue receiving numbers [from users input] until
a zero is entered. When a zero is entered, the program should output how many positive and how
many negative numbers have been entered, and then stop.
So far I've only been able to enter one number at a time in the textfield and only been able to output one value that is either positive or negative.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Exercise Two</title>
<link href="ex2.css" rel="stylesheet">
<script type="text/javascript" src="ex2.js"></script>
</head>
<body>
Enter number (Press 0 to stop)
<input type="text" id="num">
<button onclick="check()">Submit</button>
</body>
</html>
Javascript
function check(){
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('input');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
var x = parseInt(document.getElementById("num").value);
var posCount = 0;
var negCount = 0;
if (x > 0) {
posCount++;
}else{
negCount++;
}
alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount);
}
You could try appending the data to a hidden input element:
function check() {
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('input');
btnClear.addEventListener('click', () => {
inputs.forEach(input => input.value = '');
});
var x = parseInt(document.getElementById("num").value);
var totals = document.querySelector("#totals");
var posCount = totals.dataset.positives;
var negCount = totals.dataset.negatives;
if (x === 0) {
alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount);
totals.dataset.positives = 0;
totals.dataset.negatives= 0;
} else if (x > 0) {
totals.dataset.positives = ++posCount;
} else {
totals.dataset.negatives= ++negCount;
}
}
<p>Enter number (Press 0 to stop)</p>
<input type="text" id="num">
<input type="hidden" id="totals" data-positives='0' data-negatives='0'>
<button onclick="check()">Submit</button>
UPDATE
To achieve this, you can create a positive and negative variable outside of the count function and then check each input value; if the value entered zero, you can call your alert function and print the result.
Here is the working code:
var posCount = 0;
var negCount = 0;
function printOutput () {
alert("Positive numbers: " + posCount + "\nNegative numbers: " + negCount);
}
function check(){
let btnClear = document.querySelector('button');
let inputs = document.querySelectorAll('input');
var x = parseInt(document.getElementById("num").value);
document.getElementById("num").value = ''
if (x > 0) {
posCount++;
}else if (x < 0){
negCount++;
} else {
printOutput();
// re-initiate value
posCount = 0;
negCount = 0;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Exercise Two</title>
<link href="ex2.css" rel="stylesheet">
<script type="text/javascript" src="ex2.js"></script>
</head>
<body>
Enter number (Press 0 to stop)
<input type="text" id="num">
<button id="submit-btn" onclick="check()">Submit</button>
</body>
</html>
This is supposed to be a dice game where 2 people click to roll dice and they add what they get until they reach the goal. Their score resets if they roll over 9 though. Images of dice are supposed to pop up and show what they rolled. I know the images are not on here but it still shows that there should an image there with the error symbol. I am having trouble with the second image not showing up which should come from the SetPic2 function. Any help would be appreciated. Also, the PASS buttons are supposed the pass the person's turn to the other player but the main problem is the images.
//console.log("file loaded");
//var p1Button = document.getElementById("p1");
var p1Button = document.querySelector("#p1");
var p2Button = document.querySelector("#p2");
var P1Pass = document.querySelector("P1Pass");
var P2Pass = document.querySelector("P2Pass");
var setButton = document.querySelector("#set");
var resetButton = document.querySelector("#reset");
var diceImage = document.querySelector("img");
var diceImage2 = document.querySelector("img2");
var p1Total = document.querySelector("#p1score");
var p2Total = document.querySelector("#p2score");
var targetScore = document.querySelector("#tscore");
var newScore = document.querySelector("#newtarget");
var num = 0,
num2 = 0,
p1val = 0,
p2val = 0,
target;
var playgame = true;
target = Number(targetScore.textContent); //convert the string to num
p1Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p1val = p1val + num + num2;
p1Total.textContent = p1val;
setButton.disabled = true;
p1Button.disabled = true;
p2Button.disabled = false;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p1val = 0;
}
if (p1val >= target) {
playgame = false;
p1Total.classList.add("winner");
stopGame();
}
}
});
p2Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p2val = p2val + num + num2;
p2Total.textContent = p2val;
setButton.disabled = true;
p1Button.disabled = false;
p2Button.disabled = true;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p2val = 0;
}
if (p2val >= target) {
playgame = false;
p2Total.classList.add("winner");
stopGame();
}
}
});
/*P1Pass.addEventListener("click", function(){
p1Button.disabled= true;
p2Button.disabled = false;
});
P2Pass.addEventListener("click", function(){
p1Button.disabled = false;
p2Button.disabled = true;
});*/
setButton.addEventListener("click", function() {
targetScore.textContent = newScore.value;
target = Number(targetScore.textContent);
setButton.disabled = true;
newScore.disabled = true;
});
resetButton.addEventListener("click", function() {
p1Button.disabled = false;
p2Button.disabled = true;
p1Total.textContent = "0";
p2Total.textContent = "0";
targetScore.textContent = "25";
setButton.disabled = false;
newScore.disabled = false;
p1Total.classList.remove("winner");
p2Total.classList.remove("winner");
playgame = true;
p1val = 0;
p2val = 0;
target = 25;
});
function stopGame() {
p1Button.disabled = true;
p2Button.disabled = true;
setButton.disabled = true;
newScore.disabled = true;
}
function setPic(val) {
if (val == 1) {
diceImage.src = "1.png";
} else if (val == 2) {
diceImage.src = "2.png";
} else if (val == 3) {
diceImage.src = "3.png";
} else if (val == 4) {
diceImage.src = "4.png";
} else if (val == 5) {
diceImage.src = "5.png";
} else if (val == 6) {
diceImage.src = "6.png";
}
}
function setPic2(val2) {
if (val2 == 1) {
diceImage2.src = "1.png";
} else if (val2 == 2) {
diceImage2.src = "2.png";
} else if (val2 == 3) {
diceImage2.src = "3.png";
} else if (val2 == 4) {
diceImage2.src = "4.png";
} else if (val2 == 5) {
diceImage2.src = "5.png";
} else if (val2 == 6) {
diceImage2.src = "6.png";
}
}
.winner {
color: green;
background-color: yellow;
}
;
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap
.min.css" integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="gamestyle.css">
<title>Dice Game</title>
</head>
<body>
<div class="container">
<br>
<h1> <span id="p1score">0</span> vs. <span id="p2score">0</span> </h1>
<br>
<p>Target-Score: <span id="tscore">25</span></p>
<br>
<button class="btn btn-success" id="p1"> Player One </button>
<button class="btn btn-warning" id="p2"> Player Two </button>
<br><br>
<button class="btn btn-secondary" id="P1Pass">PASS</button>
<button class="btn btn-secondary" id="P2Pass">PASS</button>
<br><br> New Target: <input type="number" id="newtarget">
<br><br>
<button class="btn btn-primary" id="set"> Set </button>
<button class="btn btn-danger" id="reset"> Reset </button>
<br><br>
<img src="">
<img src="">
</div>
<script src="gamefunction.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min
.js" integrity="sha384-
Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.m
in.js" integrity="sha384-
wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Your selector will not finding your second image element.
var diceImage2 = document.querySelector("img2");
You could give your images IDs and reference them directly:
HTML
<img id="die1" src="" />
<img id="die2" src="" />
JS
var diceImage1 = document.getElementById('die1');
var diceImage2 = document.getElementById('die2');
When I click on selected option product price update shows wrong.
Here is my code
<div class="container">
<div class="row">
<div class="col-md-6">Initial Price: <span id="thisIsOriginal" class="">$45,000.00</span></div>
<div class="col-md-6">Total: <span id="total">$45,000.00</span></div>
</div>
<div class="row">
<select class="optionPrice" name="select-1">
<option value="">Please Select</option>
<option data-price="2,000.00" value="20">+$2,000.00</option>
</select>
</div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.optionPrice').change(function () {
var OriginalPrice = $('#thisIsOriginal').text();
var OriginalCurrency = OriginalPrice.substring(0, 1);
OriginalPrice = OriginalPrice.substring(1);
var total = 0;
$('.optionPrice').each(function () {
if ($(this).find('option:selected').attr('data-price') != 0 && $(this).find('option:selected').attr('data-price') != undefined) {
console.log($('option:selected', this).attr("data-price"));
total += parseFloat($('option:selected', this).attr('data-price'));
}
});
var newTotal = parseFloat(OriginalPrice) + parseFloat(total);
$('#total').text('$' + newTotal.toFixed(2));
});
});
</script>
How to solve this issue.I want after select the price shows 47,000.
The problem with your code is,
Your price contains , inside it. So after parseFloat() the values after the comma is getting truncated. You need to remove the commas before using parseFloat.
Changes need on the following lines,
total += parseFloat($('option:selected', this).attr('data-price').replace(/,/g, ""));
and
var newTotal = parseFloat(OriginalPrice.replace(/,/g, "")) + parseFloat(total);
Updated Fiddle
$('.optionPrice').change(function() {
var OriginalPrice = $('#thisIsOriginal').text();
var OriginalCurrency = OriginalPrice.substring(0, 1);
OriginalPrice = OriginalPrice.substring(1);
var total = 0;
$('.optionPrice').each(function() {
if ($(this).find('option:selected').attr('data-price') != 0 && $(this).find('option:selected').attr('data-price') != undefined) {
console.log($('option:selected', this).attr("data-price"));
total += parseFloat($('option:selected', this).attr('data-price').replace(/,/g, ""));
}
});
var newTotal = parseFloat(OriginalPrice.replace(/,/g, "")) + parseFloat(total);
$('#total').text('$' + newTotal.toFixed(2));
});
Edit for Getting comma separated value,
$('.optionPrice').change(function() {
var OriginalPrice = $('#thisIsOriginal').text();
var OriginalCurrency = OriginalPrice.substring(0, 1);
OriginalPrice = OriginalPrice.substring(1);
var total = 0;
$('.optionPrice').each(function() {
if ($(this).find('option:selected').attr('data-price') != 0 && $(this).find('option:selected').attr('data-price') != undefined) {
console.log($('option:selected', this).attr("data-price"));
total += parseFloat($('option:selected', this).attr('data-price').replace(/,/g, ""));
}
});
var newTotal = parseFloat(OriginalPrice.replace(/,/g, "")) + parseFloat(total);
newTotal = numberWithCommas(newTotal);
$('#total').text('$' + newTotal + ".00");
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
I have worked for a while on this code for learning purposes. I finally got the program to work, however when you "roll the dice", it only allows the dice to be rolled 1 time; If you wish to roll the dice a second time you must refresh the screen.
I am trying to build a reset function for this program so that I can roll the dice as many times as I wish without a screen-refresh.
I have built the reset function, but It is not working... It clear's the DIV's, but doesn't allow the program to be executed again.
Can someone please help me out?
*I am a semi-noobie at Javascript, I am making programs like this to practice my skills.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Rolling</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<h1>Roll the Dice!</h1>
<h2>By: Jeff Ward</h2>
</header>
<h3>Setup your Dice!</h3>
<div id="left">
<form id="numberOfDiceSelection">
Number Of Dice Used:
<br>
<input id="numberOfDice" type="text" name="numberOfDice">
</form>
</div>
<div id="right">
<form id="diceSidesSelection">
Number of sides on each dice:
<br>
<input id="diceSides" type="text" name="diceSides">
</form>
</div>
<button type="button" onclick="roll()">Roll the Dice!</button>
<button type="button" onclick="reset()">Reset Roll</button>
<div id="output">
</div>
<div id="output1">
</div>
<script src="js/script.js"></script>
</body>
</html>
JavaScript:
function roll() {
var text = "";
var sides = +document.getElementById("diceSides").value;
var dice = +document.getElementById("numberOfDice").value;
var rolls = [];
// --------Ensures both Numbers are Intergers-----------
if (isNaN(sides) || isNaN(dice)) {
alert("Both arguments must be numbers.");
}
// --------Loop to Print out Rolls-----------
var counter = 1;
do {
roll = Math.floor(Math.random() * sides) + 1;
text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
counter++;
rolls.push(roll);
}
while (counter <= dice)
document.getElementById("output").innerHTML = text;
// --------Double Determination-----------
var cache = {};
var results = [];
for (var i = 0, len = rolls.length; i < len; i++) {
if (cache[rolls[i]] === true) {
results.push(rolls[i]);
} else {
cache[rolls[i]] = true;
}
// --------Print amount of Doubles to Document-----------
}
if (results.length === 0) {} else {
document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
}
}
// --------RESET FUNCTION-----------
function reset() {
document.getElementById("output1").innerHTML = "";
document.getElementById("output").innerHTML = "";
document.getElementById("diceSides").value = "";
document.getElementById("numberOfDice").value = "";
text = "";
rolls = [];
}
Thank you!!
JSFiddle Link = https://jsfiddle.net/kkc6tpxs/
I rewrote and did what you were trying to do:
https://jsfiddle.net/n8oesvoo/
var log = logger('output'),
rollBtn = getById('roll'),
resetBtn = getById('reset'),
nDices = getById('numofdices'),
nSides = getById('numofsides'),
dices = null,
sides = null,
rolls = [],
doubles=0;
rollBtn.addEventListener('click',rollHandler);
resetBtn.addEventListener('click', resetHandler);
function rollHandler() {
resetView();
sides = nSides.value;
dices = nDices.value;
doubles=0;
rolls=[];
if(validateInput()) {
log('invalid input');
return;
}
//rolling simulation
var rolled;
while (dices--) {
rolled = Math.ceil(Math.random()*sides);
log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled +'!');
rolls.push(rolled);
}
//finding doubles
//first sort: you can use any way to sort doesnt matter
rolls.sort(function(a,b){
return (a>b?1:(a<b)?0:-1);
});
for (var i =0; i < rolls.length; i++) {
if (rolls[i] == rolls[i+1]) {
doubles++;
i++;
}
}
if (doubles>0) log("You rolled " + doubles + " doubles");
}
function resetHandler(){
resetView();
nDices.value = nSides.value = '';
}
function resetView() {
getById('output').innerText = '';
}
function validateInput(){
return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
}
function logger(x) { var output = getById(x);
return function(text){
output.innerText += text + '\n';
};}
function getById(x){ return document.getElementById(x); }