The calculation result always a 'NaN' - javascript

let z = document.getElementById('id_z')
let x = document.getElementById('id_x')
let y = document.getElementById('id_y')
$("#id_a, #id_b, #id_c, #id_d, #id_e").keyup(function () {
let a = $('#id_a').val()
let b = $('#id_b').val()
let c = $('#id_c').val()
let d = $('#id_d').val()
let e = $('#id_e').val()
z.value = ((c * 3.175) / a).toFixed(0)
x.value = (b*e)+(d*(e - 1))+15
// y variable throws the error
y.value = ((c*3.175) - (a * z))/z
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Value A:</label>
<input type="number" class="numberinput form-control" required="" id="id_a">
<label>Value B:</label>
<input type="number" class="numberinput form-control" required="" id="id_b">
<label>Value C:</label>
<input type="number" class="numberinput form-control" required="" id="id_c">
<label>Value D:</label>
<input type="number" class="numberinput form-control" required="" id="id_d">
<label>Value E:</label>
<input type="number" class="numberinput form-control" required="" id="id_e">
<div>
<label>Value Z:</label>
<input type="number" class="numberinput form-control" required="" id="id_z">
<label>Value x:</label>
<input type="number" class="numberinput form-control" required="" id="id_x">
<label>Value Y:</label>
<input type="number" class="numberinput form-control" required="" id="id_y">
</div>
I am creating a calculation process using JavaScript based on what the user input and delivering the result. When I try to put a number in "gear", it shows the error in the console "specified value cannot be parsed or is out of range".
const z = document.getElementById('id_z')
const x = document.getElementById('id_x')
const y = document.getElementById('id_y')
$("#id_c, #id_d, #id_e, #id_a, #id_b").keyup(function () {
const a = $('#id_a').val()
const b = $('#id_b').val()
const c = $('#id_c').val()
const d = $('#id_d').val()
const e = $('#id_e').val()
z.value = ((c * 3.175) / a).toFixed(0)
x.value = (a*e)+(d*(e - 1)+15)
// y variable throws the error
y = ((c*3.175) - (a * z))/z
console.log(y)
console.log(typeof(y))
});
For z and x looks fine but the calculation result for X always throws NaN. I need some advice on this problem, Thank you.

a) .val() provides value in string format so you have to convert it into numbers. So use parseFloat.
b) Instead of using constant use var or let as the constant value cannot be changed each time the different input values change.
c) As x,y,z are DOM elements so you can not use them directly in your calculation. You need to change your code like below.
Working snippet:
var z = document.getElementById('id_z')
var x = document.getElementById('id_x')
var y = document.getElementById('id_y')
$("#id_c, #id_d, #id_e, #id_a, #id_b").keyup(function() {
var a = parseFloat($('#id_a').val()) || 0;
var b = parseFloat($('#id_b').val()) || 0;
var c = parseFloat($('#id_c').val()) || 0;
var d = parseFloat($('#id_d').val()) || 0;
var e = parseFloat($('#id_e').val()) || 0;
var first = ((c * 3.175) / a).toFixed(0);
var second = (a * e) + (d * (e - 1) + 15);
var third = ((c * 3.175) - (a * first)) / first;
z.value = first;
x.value = second;
y.value = !isNaN(third) ? third : 0;
});
input[type="text"]
{
width:90%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br>
id_a<input type="text" id="id_a">
<br> id_b
<input type="text" id="id_b">
<br> id_c
<input type="text" id="id_c">
<br> id_d
<input type="text" id="id_d">
<br> id_e
<input type="text" id="id_e">
<br> id_x
<input type="text" id="id_x">
<br> id_y
<input type="text" id="id_y">
<br> id_z
<input type="text" id="id_z">
<br>

const z = document.getElementById('id_z')
const x = document.getElementById('id_x')
const y = document.getElementById('id_y')
$("#id_c, #id_d, #id_e, #id_a, #id_b").keyup(function () {
const a = $('#id_a').val()
const b = $('#id_b').val()
const c = $('#id_c').val()
const d = $('#id_d').val()
const e = $('#id_e').val()
z.value = ((c * 3.175) / a).toFixed(0)
// Add error handling to calculation for 'x'
if (!isNaN(a) && !isNaN(e) && !isNaN(d)) {
x.value = (a * e) + (d * (e - 1) + 15)
} else {
x.value = ''
}
// Add error handling to calculation for 'y'
if (!isNaN(c) && !isNaN(a) && !isNaN(z)) {
y.value = ((c * 3.175) - (a * z)) / z
} else {
y.value = ''
}
console.log(y.value)
console.log(typeof(y.value))
});

Just do parseFloat() in javascript to prevent this.
Below is the code for your problem:
let a = parseFloat($('#id_a').val());
let b = parseFloat($('#id_b').val());
let c = parseFloat($('#id_c').val());
let d = parseFloat($('#id_d').val());
let e = parseFloat($('#id_e').val());
Hope this work for you.

Related

How do I use an input to define decimals for other inputs?

I am trying to set the number of decimals of many inputs by using a specific input.
Here is what I am doing:
window.oninput = function(event) {
var campo = event.target.id;
// DECIMALS
if (campo == "decimalTemp") {
var i = decimalTemp.value;
ºC.value.toFixed = i;
ºK.value.toFixed = i;
ºF.value.toFixed = i;
ºRa.value.toFixed = i;
}
// TEMPERATURE
if (campo == "ºC") {
ºK.value = (ºC.value * 1 + 273.15).toFixed(i);
ºF.value = (ºC.value * 1.8 + 32).toFixed(i);
ºRa.value = ((ºC.value * 1 + 273.15) * 1.8).toFixed(i);
} else if (campo == "ºK") {
ºC.value = (ºK.value * 1 - 273.15).toFixed(2);
ºF.value = (ºK.value * 1.8 - 459.889).toFixed(2);
ºRa.value = (ºK.value * 1.8).toFixed(2);
} else if (campo == "ºF") {
ºC.value = ((ºF.value * 1 - 32) / 1.8).toFixed(2);
ºK.value = ((ºF.value * 1 + 459.67) / 1.8).toFixed(2);
ºRa.value = (ºF.value * 1 + 459.67).toFixed(2);
} else if (campo == "ºRa") {
ºC.value = (ºRa.value / 1.8 - 273.15).toFixed(2);
ºK.value = (ºRa.value / 1.8).toFixed(2);
ºF.value = (ºRa.value * 1 - 459.67).toFixed(2);
}
};
<h3>Temperature <input type="number" min="0" max="12" value="0" id="decimalTemp" name="decimal" placeholder="Decimal"> <small>Decimals<small></h3>
Celsius (ºC) <input id="ºC" type="number" min="-273.15" value="20">
<br> Kelvin (K) <input id="ºK" type="number" min="0" value="293">
<br> Farenheit (ºF) <input id="ºF" type="number" min="-459.67" value="68">
<br> Rankine (ºRa) <input id="ºRa" type="number" min="0" value="528">
In summary, I would like to know if this construction is correct:
var i = decimalTemp.value;
ºC.value.toFixed = i;
I already tried something like:
ºC.value.toFixed(i);
But didn't work. Any idea where am I wrong?

How can I display all guessed numbers in this lottery function?

I've created some simple lottery function in JS. All works fine.
The only issue I'm facing is how to display all numbers which have been guessed?
I have 6 independent spaces where numbers must be provided and my goal is to display the rolled number from random space, it must be just provided in one of the 6 spaces. That works for me, but only 1 number displays.
I'm looking for solution how to display all the guessed numbers?
function losowanie1() {
var wybor = 6;
var dostepne = 6;
r = new Array(dostepne)
var xd0 = document.getElementById("pole1").value
var xd1 = document.getElementById("pole2").value
var xd2 = document.getElementById("pole3").value
var xd3 = document.getElementById("pole4").value
var xd4 = document.getElementById("pole5").value
var xd5 = document.getElementById("pole6").value
y = new Array(6)
y[0] = xd0
y[1] = xd1
y[2] = xd2
y[3] = xd3
y[4] = xd4
y[5] = xd5
z = new Array(6)
for (var i = 0; i <= dostepne - 1; i++) {
r[i] = Math.floor((Math.random() * (49 - 1)) + 1);
if ((y[i] == r[0]) || (y[i] == r[1]) || (y[i] == r[2]) || (y[i] == r[3]) || (y[i] == r[4])) {
document.getElementById("zatw").innerHTML = y[i]
}
}
document.getElementById("wysw").innerHTML = r;
}
<div id="wysw"></div>
<div id="dupa">
<input type="text" id="pole1" /><input type="text" id="pole2" /><input type="text" id="pole3" /><input type="text" id="pole4" /><input type="text" id="pole5" /><input type="text" id="pole6" />
<br></br>
<input type="reset" id="tak" value="zatwierdz" onclick="losowanie1();" />
<br></br>
<div id="zatw"></div>
What the below still misses is to make sure the user don't repeats numbers in the inputs.
I won't do that since I would neither use inputs for that purpose, but rather predefined checkboxes (yes, 38 checkboxes) and make sure , on submit, exactly 6 are checked.
Anyways, hope this might be helpful:
function lottoGenerate(min, max) {
// Shuffle: https://stackoverflow.com/a/6274381/383904
const a = Array.from({length: max}, (_, v) => v + 1);
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a.slice(0, min);
}
function play() {
const guessed_nums = [];
const lotto_nums = lottoGenerate(6, 38); // Generate 6 random unique lotto numbers
const player_nums = Array.from(document.querySelectorAll('.num')).map(el => {
const n = parseInt(el.value, 10);
const isGuessed = lotto_nums.includes(n);
if (isGuessed) {
guessed_nums.push(n); // Insert the guessed number!
el.style.background = 'lightgreen';
} else {
el.style.background = 'red'
}
return n
});
document.getElementById('gen').textContent = lotto_nums.join(', ');
document.getElementById('player').textContent = player_nums.join(', ');
document.getElementById('response').innerHTML = `
You guessed ${guessed_nums.length} numbers!<br>
The numbers are: ${guessed_nums.join(', ')}
`;
}
document.getElementById('play').addEventListener('click', play);
<input class="num" type="number" min=1 max=38 value="1">
<input class="num" type="number" min=1 max=38 value="2"><br>
<input class="num" type="number" min=1 max=38 value="3">
<input class="num" type="number" min=1 max=38 value="4"><br>
<input class="num" type="number" min=1 max=38 value="5">
<input class="num" type="number" min=1 max=38 value="26"><br>
<button id="play">PLAY LOTTO 6/38</button>
<div>Numbers: <span id="gen"></span></div>
<div>User played: <span id="player"></span></div>
<div id="response"></div>

Get Value From Disabled Textfield Javascript

function pretest() {
var a = document.getElementById('pre').value;
var result = parseInt(a);
if (a <= 50) {
document.getElementById('val').value = 1;
}else if(50<a && a<= 80){
document.getElementById('val').value = 2;
}else{
document.getElementById('val').value = 3;
}
}
function posttest(){
var a = document.getElementById('post').value;
var result = parseInt(a);
if (a <= 50) {
document.getElementById('val1').value = 1;
}else if(50<a && a<= 80){
document.getElementById('val1').value = 2;
}else{
document.getElementById('val1').value = 3;
}
}
function all(){
var a = document.getElementById('val').value;
var b = document.getElementById('val1').value;
var c = parseInt(a) + parseInt(b);
if (!isNaN(c)) {
document.getElementById('total').value = c;
}
}
<input onkeyup="pretest();" type="text" id="pre" name="pretest">
<input onkeyup="all();" type="text" id="val" name="val" disabled="disabled">
<input onkeyup="posttest();" type="text" id="post" name="posttest">
<input onkeyup="all();" type="text" id="val1" name="val1" disabled="disabled">
<input onkeyup="total();" type="text" id="total" name="total" disabled="disabled">
i have 5 text field
A1 A2(value onkeyup from A1 and disabled is true)
B1 B2(value onkeyup from B1 and disabled is true)
C(A2+B2 and disabled textfield)
How to get value for C textfield ? i used onkeyup, but didn't work
There are several things amiss in your code.
never, ever use parseInt(foo) without the radix-argument, especially when foo is arbitrary input. parseInt will otherwise take input 012 and think it's an octal value you gave it. Thus, make that parseInt(a, 10) to get a decimal, or use Number(a)
onkeyup won't fire on a disabled element - how could it? Nobody will be able to press a key there, since it's disabled. What you probably want is onchange, however...
...onchange (or oninput, which is a little more trigger-happy and what I've used below) won't fire when you manually set an element's value; it doesn't in vanilla JS, nor when using jQuery's val() - you have to trigger it manually
your code example is rushed, incomplete and I had to work considerably longer and harder to understand what you want than should be necessary; regardless...
/*
Especially with function names like `all` and `total`, you will want
to make sure to set up some sort of namespacing, e.g. using the
Revealing Module Pattern or other. These functions are attached to
the global window object and can be overriden by anything and anybody,
causing at least hard-to-trace bugs, maybe worse
*/
function pretest() {
var a = document.getElementById('pre').value;
var result = parseInt(a, 10);
if (a <= 50) {
document.getElementById('val').value = 1;
} else if (50 < a && a <= 80) {
document.getElementById('val').value = 2;
} else {
document.getElementById('val').value = 3;
}
// you have to explicitly call all() here, as the input-event
// won't be fired when manually setting value
all();
}
function posttest() {
var a = document.getElementById('post').value;
var result = parseInt(a, 10);
if (a <= 50) {
document.getElementById('val1').value = 1;
} else if (50 < a && a <= 80) {
document.getElementById('val1').value = 2;
} else {
document.getElementById('val1').value = 3;
}
all()
}
function all() {
var a = document.getElementById('val').value;
var b = document.getElementById('val1').value;
var c = parseInt(a, 10) + parseInt(b, 10);
if (!isNaN(c)) {
document.getElementById('total').value = c;
}
total();
}
total = function() {
//TODO implement
}
document.getElementById('pre').addEventListener('input', window.pretest);
document.getElementById('post').addEventListener('input', window.posttest);
<label for="pre">PRE</label><br>
<input type="text" id="pre" name="pretest">
<br><br>
<label for="val">val</label><br>
<input type="text" id="val" name="val" disabled="disabled">
<br><br>
<label for="post">POST</label><br>
<input type="text" id="post" name="posttest">
<br><br>
<label for="val1">val1</label><br>
<input type="text" id="val1" name="val1" disabled="disabled">
<br><br>
<label for="total">TOTAL</label><br>
<input type="text" id="total" name="total" disabled="disabled">
You can get value as from normal text input
function myFunction(){
document.getElementById("textPlace").disabled = true;
console.log(document.getElementById("textPlace").value)
}
<input type="text" onkeyup="myFunction()" id="textPlace">

javaScript got stuck with converting bytes

so I've got a bit of the problem. I am trying to make a function in wich : human clicks on input box with mouse and types some random numbers in bytes and that number should be convert and shown in two other boxes such as MegaBytes and KiloBytes. So my problem is that Javascript shows me error :
Cannot set property 'value' of null
at convert (script.js:7)
at HTMLInputElement.onkeyup
here is my code so far:
function convert(inputas)
{
var i;
if(inputas == "B")
{
i = document.getElementById("baitas").value / 1000;
document.getElementById("kiloBaitas").value = i;
}
else if(inputas == "KB")
{
i = document.getElementById("kiloBaitas").value * 1024;
document.getElementById("baitas").value = i.toFixed(2);
}
}
HTML code:
<input type="text" id="baitas" onkeyup="convert('B')placeholder="Bits">
<input type="text" id="kilobaitas"
`onkeyup="convert('KB')"placeholder="Kilobits">
<input type="text" id="megabaitas" onkeyup="convert('MB')"
placeholder="Mbits">
<script src="script.js"></script>
when comparing your javascript with the html. the kilobaitis element is not spelt with a consistent case.
JavaScript is case sensitive.
function convert(inputas) {
var i;
if (inputas == "B") {
i = document.getElementById("baitas").value / 1000;
document.getElementById("kilobaitas").value = i;
} else if (inputas == "KB") {
i = document.getElementById("kiloBaitas").value * 1024;
document.getElementById("baitas").value = i.toFixed(2);
}
}
<input type="text" id="baitas" onkeyup="convert('B')" placeholder=" Bits ">
<input type="text " id="kilobaitas" onkeyup="convert('KB')" placeholder="Kilobits ">
<input type="text " id="megabaitas" onkeyup="convert('MB')" placeholder="Mbits ">
(function() {
var elems = [],
elemsId = ['baitas','kilobaitas','megabaitas'];
function fix(a){ return ( a * 100 | 0 ) / 100 }
function convert(inputas)
{
var i;
switch(inputas)
{
case 0:
i = elems[0].value;
elems[1].value = fix( i / 1024 );
elems[2].value = fix( i / 1048576 );
break;
case 1:
i = elems[1].value;
elems[0].value = i * 1024;
elems[2].value = fix( i / 1024 );
break;
case 2:
i = elems[2].value;
elems[0].value = i * 1048576;
elems[1].value = i * 1024;
break;
}
}
for (var i=0; i < elemsId.length; i++)
{
elems[i] = document.getElementById( elemsId[i] );
elems[i].addEventListener('keyup', convert.bind(null, i) )
}
}());
<input type="text" id="baitas" placeholder=" Bits">
<input type="text" id="kilobaitas" placeholder=" Kilobits">
<input type="text" id="megabaitas" placeholder=" Mbits">

JavaScript html forms calculator not working

im trying to make a simple perimeter calculator for a projector screen.
The code should take the response from a radio button input and the diagonal length to calculate the perimeter accordingly.
here is my code atm:
<html>
<body>
<script language="javascript">
function calc() {
var form = document.forms.Calculator;
var A = Number(getSelectedValue(form.elements.A));
var B = Number(getSelectedValue(form.elements.B));
if (A = 0) {
L = 0.8;
H = 0.6;
} else if (A = 1) {
L = 0.872;
H = 0.49;
} else {
L = 0.922;
H = 0.386;
}
form.elements.Total.value = 2 * B * (L + H);
}
function getSelectedValue(flds) {
var i = 0;
var len = flds.length;
while (i < len) {
if (flds[i].checked) {
return flds[i].value;
}
i++;
}
return "";
}
</script>
<title>Calculator</title> <pre>
<form name="Calculator">
<label>A</label>
4:3: <input name="A" type="radio" onChange="calc()" value="0" checked>
16:9: <input name="A" type="radio" onChange="calc()" value="1">
2.39:1: <input name="A" type="radio" onChange="calc()" value="2">
<label>B</label>
Screen Size: <input name="B" type="text" onChange="calc()" checked>
<label>Total</label>
<input type="text" name="Total" onChange="calc()" readonly size="10"><br>
<input type="submit" value="Submit Calculation"> <input type="reset" value="Clear">
</form>
</pre>
</body>
</html>
Your function getSelectedValue is wrong. It loops trough an array of elements to see which one is checked. You are trying to do the same for B which is only one element so that is not going trough the loop and thus returns ''.
So instead of
var B = Number(getSelectedValue(form.elements.B));
try
var B = Number(form.elements.B.value);
Also, your if else statements are wrong. It should be == instead of =:
if (A == 0) {
L = 0.8;
H = 0.6;
} else if (A == 1) {
L = 0.872;
H = 0.49;
} else {
L = 0.922;
H = 0.386;
}

Categories

Resources