Sorry for such a noob problem - I've not found a solution after browsing many posts and I'm afraid I don't even know what question to ask - I'm trying to auto populate the 'sunits' input field to the value of the 'bunits' input, unless changed. I barely cobbled this together for some friends, and do apologize for the poor style and everything else. The code below is also the homepage at http://lootsim.com :
<div id="buyformdiv" class="fluid ">
<span id="pickingupspan" class="actionspan">Buying:</span>
<p># units to be bought:
<input id="bunits" type="number" step="1" onchange="update()"></p>
<p>
Cost per unit :
<input id="cunits" type="number" step="0.01" onchange="update()"></p>
<p>
Overhead :
<input id="cxbship" type="number" step="0.01" onchange="update()"></p>
</div>
<div id="sellformdiv" class="fluid ">
<span id="gettingridspan" class="actionspan">Selling:</span>
<p># units to be sold:
<input id="sunits" type="number" step="1" onchange="update()"></p>
<p>
selling for ($ each) :
<input id="sprice" type="number" step="0.01" onchange="update()"></p>
<p>
Frequency :
<select id="sfreq" onchange="update()">
<option value="1">Once</option>
<option value="7">Week</option>
<option value="31">Month (31 days)</option>
<option value="365">Year</option>
</select>
</p>
</div>
Javascript"
var bunits, cunits, cxb, cxbship, btotal, sunits, sfreq, sprice, net, profit;
function update() {
var bunits = document.getElementById('bunits').value;
var cunits = document.getElementById('cunits').value;
var cunits = parseFloat(cunits).toFixed(2);
var cxbship = document.getElementById('cxbship').value;
var cxbship = parseFloat(cxbship).toFixed(2);
var cxb = bunits * cunits;
var cxb = parseFloat(cxb).toFixed(2);
var btotal = parseFloat(cxb) + parseFloat(cxbship);
var btotal = parseFloat(btotal).toFixed(2);
var sunits = document.getElementById('sunits').value;
var sprice = document.getElementById('sprice').value;
var sprice = parseFloat(sprice).toFixed(2);
var sfreq = document.getElementById('sfreq').value;
var sunitxp = sunits * sprice;
var sunitxp = parseFloat(sunitxp).toFixed(2);
var salesxdays = sunitxp * sfreq;
var salesxdays = parseFloat(salesxdays).toFixed(2);
//populate numbers in results window
if (bunits > 0) {
document.getElementById('bunitsspan').innerHTML = "Buying " + bunits + " units";
document.getElementById('sunits').value = bunits;
}
if (cunits > 0) {
document.getElementById('costspan').innerHTML = "at $" + cunits + " per unit";
}
if (cxb > 0) {
document.getElementById('cxbspan').innerHTML = "Subtotal: $" + cxb;
}
if (cxbship > 0) {
document.getElementById('cxbshipspan').innerHTML = "Overhead: " + cxbship;
}
if (btotal > 0) {
document.getElementById('subtotalspan').innerHTML = "<b>Total: $" + btotal + "</b>";
}
//populate income in results span
if (sunits > 0) {
document.getElementById('sunitsspan').innerHTML = "Selling " + sunits + " units";
}
if (sprice > 0) {
document.getElementById('sellcostspan').innerHTML = "for $" + sprice + " each";
}
if (sunitxp > 0) {
document.getElementById('sunitxpspan').innerHTML = "Subtotal: $" + sunitxp;
}
if (sfreq > 0 ) {
if ((sfreq == 1) && (sprice > 0)){
document.getElementById('sellfreqspan').innerHTML = "all units";
} else if (sfreq == 7) {
document.getElementById('sellfreqspan').innerHTML = "every day for a week";
} else if (sfreq == 31) {
document.getElementById('sellfreqspan').innerHTML = "every day for a month";
} else if (sfreq == 365) {
document.getElementById('sellfreqspan').innerHTML = "every day for a year";
}
}
if (salesxdays > 0) {
document.getElementById('salesxdays').innerHTML = "Total: $" + salesxdays;
}
}
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>
I have been studying JavaScript and experiment with some things. I have build a small application (see code below). Everything is going well untill the function eindResultaat(). Here it seems that there is something with resultaat3 (it is NaN) but I can not figure out why. resultaat1 and resultaat2 are getting processed in the same way and there it goes fine.
var resultatenArray = [];
var eindcijfer, eRes1, eRes2, eRes3, resultaat1, resultaat2, resultaat3;
function berekening1() {
resultaat1 = document.getElementById("eersteTentamen").value;
console.log("Dit is resultaat1 " + resultaat1);
if ((resultaat1 == "GR") || (resultaat1 == "gr")) {
document.getElementById("res1").innerHTML = "Geen resultaat";
resultaat1 = resultaat1 || 0;
//eRes1 = 0.0;
} else {
let res1 = document.getElementById("res1");
res1.innerHTML = resultaat1;
res1.style.color = resultaat1 >= 5.5 ? 'green' : 'red';
document.getElementById("res1").innerHTML = resultaat1;
//eRes1 = resultaat1;
resultatenArray.push(resultaat1);
console.log(resultatenArray);
}
}
function berekening2() {
resultaat2 = document.getElementById("tweedeTentamen").value;
console.log("Dit is resultaat2 " + resultaat2);
if ((resultaat2 == "GR") || (resultaat2 == "gr")) {
document.getElementById("res2").innerHTML = "Geen resultaat";
eRes2 = 0.0;
} else {
let res2 = document.getElementById("res2");
res2.innerHTML = resultaat2;
res2.style.color = resultaat2 >= 5.5 ? 'green' : 'red';
document.getElementById("res2").innerHTML = resultaat2;
//eRes2 = resultaat2;
resultatenArray.push(resultaat2);
console.log(resultatenArray);
}
}
function berekening3() {
resultaat3 = document.getElementById("derdeTentamen").value;
console.log("Dit is resultaat3 " + resultaat3);
if ((resultaat3 == "GR") || (resultaat3 == "gr")) {
document.getElementById("res3").innerHTML = "Geen resultaat";
var resultaat3 = 0.0;
//eRes3 = 0;
console.log(resultaat3);
} else {
let res3 = document.getElementById("res3");
res3.innerHTML = resultaat3;
res3.style.color = resultaat3 >= 5.5 ? 'green' : 'red';
document.getElementById("res3").innerHTML = resultaat3;
//eRes3 = resultaat3;
resultatenArray.push(resultaat3);
console.log(resultatenArray);
}
console.log(isNaN(resultaat3));
}
function eindResultaat() {
var aantalDeelTentamens = resultatenArray.length;
console.log(aantalDeelTentamens);
console.log("resultaten: " + resultaat1, resultaat2, resultaat3);
//console.log("eRes resultaten:" + eRes1, eRes2, eRes3);
//parseFloat(resultaat1);
//parseFloat(resultaat2);
//parseFloat(resultaat3);
console.log(isNaN(resultaat1));
console.log(isNaN(resultaat2));
console.log(isNaN(resultaat3));
eindcijfer = ((resultaat1 + resultaat2 + resultaat3) / aantalDeelTentamens).toFixed(1);
//var eindcijfer = ((eRes1 + eRes2 + eRes3)/aantalDeelTentamens).toFixed(1);
console.log(eindcijfer);
console.log(isNaN(eindcijfer));
document.getElementById("eindresultaat").innerHTML = eindcijfer;
}
Resultaat <b>eerste</b> deeltentamen: <input type="text" value="" id="eersteTentamen"><input type="submit" name=buttonResultaat1 value="Resultaat bevestigen" onclick="berekening1()"><br><br> Resultaat <b>tweede</b> deeltentamen: <input type="text" value=""
id="tweedeTentamen"><input type="submit" name=buttonResultaat2 value="Resultaat bevestigen" onclick="berekening2()"><br><br> Resultaat <b>derde</b> deeltentamen: <input type="text" value="" id="derdeTentamen"><input type="submit" name=buttonResultaat3
value="Resultaat bevestigen" onclick="berekening3()"><br><br>
<hr> Resultaat <b>eerste</b> deeltentamen: <span id="res1"></span><br> Resultaat <b>tweede</b> deeltentamen: <span id="res2"></span><br> Resultaat <b>derde</b> deeltentamen: <span id="res3"></span><br><br>
<hr>
<br>
<input type="submit" name=eindresultaat value="Bereken eindresultaat" onclick="eindResultaat()"><br><br>
<b>Het eindresultaat is: </b> <span id="eindresultaat"></span>
Indeed, it was deleting the var at some places so the code works. No I am busy with what to do if someone makes 2 test in stead of 3. So the average must be calculated over 2 tests.
How to correctly get input data and call it in the function?
I try to call this function in submit button, but I can't see any action.
<input style="display:none;" class="form-control col-md-5 col-8" id="pesel" minlenght="11"
maxlength="11"
type="text" name="pesel"
placeholder="PESEL" required>
<p><input class="submit-button" type='submit' name='submit' value='Wyślij' onclick="isValidPesel()"></p>
<span id="error"></span>
<script>
function isValidPesel(pesel) {
function validatepesel(pesel) {
var reg = /^[0-9]{11}$/;
if (reg.test(pesel) == false) {
console.log("error");
document.getElementById('error').innerHTML = 'Niepoprawny numer pesel';
return false;
} else {
var digits = ("" + pesel).split("");
if ((parseInt(pesel.substring(4, 6)) > 31) || (parseInt(pesel.substring(2, 4)) > 12))
return false;
console.log("Error");
document.getElementById('error').innerHTML = 'Niepoprawny numer pesel';
var checksum = (1 * parseInt(digits[0]) + 3 * parseInt(digits[1]) + 7 * parseInt(digits[2]) + 9 * parseInt(digits[3]) + 1 * parseInt(digits[4]) + 3 * parseInt(digits[5]) + 7 * parseInt(digits[6]) + 9 * parseInt(digits[7]) + 1 * parseInt(digits[8]) + 3 * parseInt(digits[9])) % 10;
if (checksum == 0) checksum = 10;
checksum = 10 - checksum;
return (parseInt(digits[10]) == checksum);
}
}
var pesel = document.getElementById("pesel").value;
console.log(pesel);
}
</script>
This should do the trick: (No change in the HTML)
<input style="display:none;" class="form-control col-md-5 col-8" id="pesel" minlenght="11" maxlength="11" type="text" name="pesel" value="324983274823" placeholder="PESEL" required>
<p>
<input class="submit-button" type='submit' name='submit' value='Wyślij' onclick="isValidPesel()">
</p>
<span id="error"></span>
JavaScript: Error was you not calling the validatepesel function at the end.
function isValidPesel(pesel) {
function validatepesel(pesel) {
var reg = /^[0-9]{11}$/;
if (reg.test(pesel) == false) {
console.log("error");
document.getElementById('error').innerHTML = 'Niepoprawny numer pesel';
return false;
} else {
var digits = ("" + pesel).split("");
if ((parseInt(pesel.substring(4, 6)) > 31) || (parseInt(pesel.substring(2, 4)) > 12))
return false;
console.log("Error");
document.getElementById('error').innerHTML = 'Niepoprawny numer pesel';
var checksum = (1 * parseInt(digits[0]) + 3 * parseInt(digits[1]) + 7 * parseInt(digits[2]) + 9 * parseInt(digits[3]) + 1 * parseInt(digits[4]) + 3 * parseInt(digits[5]) + 7 * parseInt(digits[6]) + 9 * parseInt(digits[7]) + 1 * parseInt(digits[8]) + 3 * parseInt(digits[9])) % 10;
if (checksum == 0) checksum = 10;
checksum = 10 - checksum;
return (parseInt(digits[10]) == checksum);
}
}
var pesel = document.getElementById("pesel").value;
validatepesel(pesel);
}
Method 1:
<input class="submit-button" type='submit' name='submit' value='Wyślij' onclick="isValidPesel(this)">
<script>
function isValidPesel(element) {
console.log(element.value);
}
</script>
Method 2:
<input type="hidden" value="Wyślij" id="myInput">
<input class="submit-button" type='submit' name='submit' onclick="isValidPesel(this)">
<script>
function isValidPesel() {
var str = $("#myInput").val();
console.log(str);
}
</script>
I created a function that calculates the final cost of an order, and I'm trying to display it in a text box. However, the text box keeps returning "$ NaN" and I cannot find the error. I'm a very beginning student of html and js, so any explanation is appreciated.
function costCalculator() {
totalCost = (totalCost + burgerOnePrice * Number(burgerOne.value));
totalCost = (totalCost + burgerTwoPrice * Number(burgerTwo.value));
totalCost = (totalCost + burgerThreePrice * Number(burgerThree.value));
totalCost = totalCost * (1 + tip);
if (useCard == 1) {
if (Number(balance.value) >= totalCost) {
totalCost = 0;
cardBalance = cardBalance - totalCost;
balance.value = cardBalance;
finalCost.value = totalCost;
} else {
totalCost = (totalCost - Number(balance.value));
balance.value = 0;
finalCost.value = totalCost;
}
}
document.getElementById("finalCost").value= "$ "+parseFloat(this.totalCost).toFixed(2);
document.getElementById("balance").value= "$ "+parseFloat(this.balance).toFixed(2);
}
Here's the button that calls the function and the text box that I want it to appear it:
<button id="totalSales" onclick = "costCalculator();" >Calculate Total</button>
<br><br>
<input type="text" id="finalCost" value="" size="3" readonly="true" />
You should check console log or run debugger (F12) first - lot of bugs / missing info at least in question here, but in case I put something instead of all missing items, it starts to run without code errors at least ;-)
var burgerOnePrice = 123,
burgerTwoPrice = 234,
burgerThreePrice = 345,
tip = 456,
useCard = 1;
function costCalculator() {
var totalCost = 0,
f = document.forms[0],
balance = { value: f.balance.value.replace(/[$ ]/,'') },
burgerOne = f.burgerOne,
burgerTwo = f.burgerTwo,
burgerThree = f.burgerThree;
totalCost = (totalCost + burgerOnePrice * Number(burgerOne.value));
totalCost = (totalCost + burgerTwoPrice * Number(burgerTwo.value));
totalCost = (totalCost + burgerThreePrice * Number(burgerThree.value));
totalCost = totalCost * (1 + tip);
if (useCard == 1) {
if (Number(balance.value) >= totalCost) {
totalCost = 0;
cardBalance = cardBalance - totalCost;
balance.value = cardBalance;
f.finalCost.value = totalCost;
} else {
totalCost = (totalCost - Number(balance.value));
balance.value = 0;
f.finalCost.value = totalCost;
}
}
document.getElementById("finalCost").value = "$ " + parseFloat(totalCost).toFixed(2);
document.getElementById("balance").value = "$ " + parseFloat(balance.value).toFixed(2);
}
<form>
<input type="button" id="totalSales" onclick = "costCalculator();" value="Calculate Total">
<br><br>
<input name="burgerOne" value="1">
<input name="burgerTwo" value="2">
<input name="burgerThree" value="3">
<input type="text" id="finalCost" value="" size="3" readonly="true" />
<input id="balance" value="$ 100000">
</form>
I have been trying to solve the following problem for the last week or so, and after many searches around the internet, and on here, haven't found an exact solution for what I am trying to achieve.
This is my first post on here, and decided to post here as this forum has saved my bacon several times!
This is what I would like to happen:
User selects the number of scouts and leaders from the dropdowns.
The first tshirts (small) is populated with the number of leaders + scouts total.
if the user selects a lesser amount from the small dropdown, then the remaining amount is used to populate the medium select list, and so on upto XXL.
The following bit of code is how far I have got so far, but it seems a bit buggy, the option values append again and again if the user changes their mind, and the medium box is showing the total options rather that total - amount of small selected.
I don't know if this is the best way or if there are any better solutions?
Here goes
<form method='post' id="wawBooking" action='processWAWBooking.php' >
<div id="groupDetails" >
<fieldset>
<legend>Group Details</legend>
<label for="noScouts">Number of scouts:</label>
<select id='noScouts' name="noScouts"></select><br />
<label for="noLeaders">Number of leaders:</label>
<select id='noLeaders' name="noLeaders"></select><br />
</fieldset>
</div>
<div style="clear: both;"></div>
<div id="tshirts">
<fieldset style="height: auto;">
<legend>T-Shirts</legend>
Total: <span id='totalTshirts'></span><br />
Amount left (Total - current total): <span id='amountLeft'></span><br />
Sum of Selected: <span id='liveTotal'></span><br />
<label for='s'>Small</label>
<select id='s'></select><br />
<label for='m'>Medium</label>
<select id='m'> </select><br />
<label for='l'>Large</label>
<select id='l'></select><br />
<label for='xl'>X-Large</label>
<select id='xl'></select><br />
<label for='xxl'>XX-Large</label>
<select id='xxl'></select><br />
</fieldset>
</div>
<input type="reset" value="Reset Form" id="reset" style="float: left;"/>
<input type="button" value="Order t-shirts" id="tshirtOrder" style="float: right;"/>
<input type="submit" value="Submit Booking" style="float: right;"/>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
var scouts = 20;
var leaders = 30;
// ignore this bit - using just to demonstrate
for (a = 0; a <= leaders; a++) {
$('#noScouts').append("<option value='" + a + "'>" + a + "</option>");
}
for (b = 0; b <= scouts; b++) {
$('#noLeaders').append("<option value='" + b + "'>" + b + "</option>");
}
// end of ignore section!
$('#wawBooking').change(function(){
var totalTshirts = parseInt($('#noLeaders').val()) + parseInt($('#noScouts').val());
var liveTotal = parseInt($('#s').val())
+ parseInt($('#m').val())
+ parseInt($('#l').val())
+ parseInt($('#xl').val())
+ parseInt($('#xxl').val());
if ($('#noScouts').val() && $('#noLeaders').val() > 0) {
$('#totalTshirts').empty().append(totalTshirts);
$('#liveTotal').empty().append(liveTotal);
for (i = 0; i <= totalTshirts; i++) {
$('#s').append('<option value="' + i + '">' + i + '</option>')
}
if ($('#s').val() > 0 && $('#s').val() < totalTshirts) {
var subSmallMinusTotal = parseInt(totalTshirts) - parseInt($('#s').val());
for (k = 0; k <= subSmallMinusTotal; k++) {
$('#m').append('<option value="' + k + '">' + k + '</option>')
}
}
}
});
</script>
Any suggestions or tips?
Many thanks in advance
Chris
Here's a possible solution. You might be able to tweak it to be more generic and generate the lists off a collection, but I think it'll get you started.
Example (JsFiddle)
HTML
<label for="noScouts">Number of scouts:</label>
<select id='noScouts' name="noScouts"></select><br />
<label for="noLeaders">Number of leaders:</label>
<select id='noLeaders' name="noLeaders"></select><br />
<label for="noSmall">s:</label>
<select id='noSmall' name="noSmall"></select>
<label for="noMed">m:</label>
<select id='noMed' name="noMed"></select>
<label for="noLarge">l:</label>
<select id='noLarge' name="noLarge"></select>
<label for="noXLarge">xl:</label>
<select id='noXLarge' name="noXLarge"></select>
<label for="noXXLarge">xxl:</label>
<select id='noXXLarge' name="noXXLarge"></select>
JS
var sizes = $('#sizes');
var numScouts = new selectRange('#noScouts', { max: 30 });
var numLeaders = new selectRange('#noLeaders', { max: 20 });
var total = new watchVal(0);
var small = new selectRange('#noSmall', { max: 0 });
var med = new selectRange('#noMed', { max: 0 });
var large = new selectRange('#noLarge', { max: 0 });
var xlarge = new selectRange('#noXLarge', { max: 0 });
var xxlarge = new selectRange('#noXXLarge', { max: 0 });
numScouts.change(zSetTotal);
numLeaders.change(zSetTotal);
total.change(function(e, total){
small.setMax(total);
});
small.change(function(){
med.setMax(total.value() - small.value());
});
med.change(function(){
large.setMax(total.value() - med.value() - small.value());
});
large.change(function(){
xlarge.setMax(total.value() - med.value() - small.value() - large.value());
});
xlarge.change(function(){
xxlarge.setMax(total.value() - med.value() - small.value() - large.value() - xlarge.value());
});
function zSetTotal(){
total.value(numScouts.value() + numLeaders.value());
}
function watchVal(initVal){
var _val = initVal;
var $_ctx = $(this);
$_ctx.value = function(newVal){
if(newVal){
_val = newVal;
$_ctx.trigger('change', _val);
}else{
return _val;
}
}
return $_ctx;
}
function selectRange(selector, options){
var _config = {
max: 10
};
var _select = null;
var _ctx = this;
function zInit(){
$.extend(_config, options);
if($(selector).is('select')){
_select = $(selector);
}else{
_select = $('<select />');
_select.appendTo(selector);
}
_ctx.repaint();
}
this.setMax = function(max){
_config.max = max;
this.repaint();
_select.trigger('change');
};
this.repaint = function(){
var prevPos = _select.find('> option:selected').index();
_select.empty();
for (var i = 0; i <= _config.max; i++) {
var option = $("<option />", {
'value': i,
'text': i
});
_select.append(option);
if(i === prevPos){
option.prop('selected', true);
}
}
};
this.value = function(){
return parseInt(_select.val(), 10);
};
this.change = function(fun){
_select.change(fun);
};
zInit();
}