Why does this function's results show up as NaN? - javascript

I have this simple piece of code:
var numb1 = document.getElementById("numb1")
var numb2 = document.getElementById("numb2")
var numb3 = document.getElementById("numb3")
var numb4 = document.getElementById("numb4")
var v1 = parseInt(numb1)
var v2 = parseInt(numb2)
var v3 = parseInt(numb3)
var v4 = parseInt(numb4)
var t = parseInt(0)
function myFunction() {
if (numb1.checked == true) {
var t = v1 + t
} else if (numb2.checked == true) {
var t = v2 + t
} else if (numb3.checked == true) {
var t = v3 + t
} else if (numb4.checked == true) {
var t = v4 + t
}
document.getElementById("demo").innerHTML = t
}
<input id="numb1" type="radio" value="10">
<input id="numb2" type="radio" value="50">
<input id="numb3" type="radio" value="80">
<input id="numb4" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
I get that I definitely could have been more efficient when making my variables, but my problem is that even after I use parseInt() to go from string to integer, the end result in demo displays NaN. Is there something wrong with the way I defined the variables, or is it the calculation of the end value?

Because parseInt( elementObject ) doesn't return a valid number.
You wanted to parse the value, with a radix
var v1 = parseInt(numb1.value, 10);
And you have to get those values inside the function, when the value has actually changed.
Also, add some semicolons, they aren't always needed, but it's good practice to add them, and don't redeclare variables
var numb1 = document.getElementById("numb1");
var numb2 = document.getElementById("numb2");
var numb3 = document.getElementById("numb3");
var numb4 = document.getElementById("numb4");
function myFunction() {
var v1 = parseInt(numb1.value, 10);
var v2 = parseInt(numb2.value, 10);
var v3 = parseInt(numb3.value, 10);
var v4 = parseInt(numb4.value, 10);
var t = 0;
if (numb1.checked) {
t = v1 + t;
} else if (numb2.checked) {
t = v2 + t;
} else if (numb3.checked) {
t = v3 + t;
} else if (numb4.checked) {
t = v4 + t;
}
document.getElementById("demo").innerHTML = t
}
<input id="numb1" type="radio" value="10">
<input id="numb2" type="radio" value="50">
<input id="numb3" type="radio" value="80">
<input id="numb4" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>

I agree with the answer by adeneo. The issue is that you are parseInting an HTML Input Element.
And you already got the answer.
But I noticed that you use if..else
So, You want only one value to be selected by the user.
So, There is a short method which also help to improve the loading speed and reduce lines of codes.
using forms
function myFunction(){
t=parseInt(document.forms[0]["num"].value);
document.getElementById("demo").innerHTML=t
}
<form>
<input id="numb1" name="num" type="radio" value="10">
<input id="numb2" name="num" type="radio" value="50">
<input id="numb3" name="num" type="radio" value="80">
<input id="numb4" name="num" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
</form>
<p id="demo"></p>

Related

How to switch functions javascript

I'd like to make something small. When you enter Celsius, the program should calculate Fahrenheit and vice-versa. But when I enter the celsius and click the button it does the vice-versa aswell. Since I'm a beginner I don't really know how not to execute function2 if function1 activates. My javascript looks like this:
JS:
function Omrekenen() {
var celsius = document.getElementById('Celsius').value;
var fahrenheit = document.getElementById('Fahrenheit').value;
var r1 = (celsius * 1.8) + 32;
var r2 = (fahrenheit / 1.8) - 32;
}
function Leeg1() {
document.getElementById('Fahrenheit').value = "";
}
function Leeg2() {
document.getElementById('Celsius').value = "";
}
<div class="Oefening">
<h1 class="Titel">Oefening 3</h1>
Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup=Leeg1()> Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
<input type="button" id="button3" value="Zet om" onclick="Omrekenen(); Vast();" class="Button">
</div>
Here's one way of doing this.
Note that I'm checking for the length of the value from the input. You can't check the truthiness (if (celsius) ...) in this case, since a value of 0 is valid, but would evaluate to false. Checking the length should work for each case.
function Omrekenen() {
var celsius = document.getElementById('Celsius').value;
var fahrenheit = document.getElementById('Fahrenheit').value;
if (celsius.length !== 0) {
document.getElementById('Fahrenheit').value = (celsius * 1.8) + 32;
} else if (fahrenheit.length !== 0) {
document.getElementById('Celsius').value = (fahrenheit / 1.8) - 32;
}
}
function Leeg1() {
document.getElementById('Fahrenheit').value = "";
}
function Leeg2() {
document.getElementById('Celsius').value = "";
}
<div class="Oefening">
<h1 class="Titel">Oefening 3</h1>
Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup=Leeg1()> Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
<input type="button" id="button3" value="Zet om" onclick="Omrekenen();" class="Button">
</div>
You can use a state variable also, but you'd also want to handle the paste action in that case.
<script>
var isCalculatingCelsius;
function Omrekenen()
{
var celsius = document.getElementById('Celsius').value;
var fahrenheit = document.getElementById('Fahrenheit').value;
if (isCalculatingCelsius){
document.getElementById('Celsius').value = (fahrenheit / 1.8) - 32;
} else {
document.getElementById('Fahrenheit').value = (celsius * 1.8) + 32;
}
}
function Leeg1(){
isCalculatingCelsius = false;
document.getElementById('Fahrenheit').value = "";
}
function Leeg2(){
isCalculatingCelsius = true;
document.getElementById('Celsius').value = "";
}
</script>
<div class="Oefening">
<h1 class="Titel">Oefening 3</h1>
Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup="Leeg1()">
Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
<input type="button" id="button3" value="Zet om" onclick="Omrekenen()" class="Button">
</div>

Javascript won't calculate

Can anyone point me in the right direction as to why my calculate button will not calculate. It doesn't even throw any of the error messages up to the screen, but my clear button does work. It's probably something small, but I cannot figure it out for the life of me -_-.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("totalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("cost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
var virusRemoval = parseFloat($("virusRemoval").value = "");
var websiteMaking = parseFloat($("websiteMaking").value = "");
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value = "");
var totalCost = parseFloat($("totalCost").value = "");
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotal" value="Calculate " onblur="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>
The reason why the loop is in there is because we were required to have a loop and I couldn't find a good reason to have one, so I used one that would always be true to get it out of the way lol. Probably will throw an infinate loop at me or something, but I'll figure that out later, I'm just trying to get the dang on thing to do something here haha. I've tried to rewrite this 2 other times and still get to the same spot, so I realize it's probably something small, and I am new to Javascript. Thank you.
The problem is that you have id="calculateTotal" in the input button. Element IDs are automatically turned into top-level variables, so this is replacing the function named calculateTotal. Simply give the function a different name from the button's ID.
You also have a typo. The ID of the Total Cost field is TotalCost, but the code uses $('totalCost') and $('cost').
It's also better to do the calculation in onclick, not onblur. Otherwise you have to click on the button and then click on something else to see the result.
In the clearValues function, there's no need to assign variables and call parseFloat. Just set each of the values to the empty string. You could also just use <input type="reset">, that resets all the inputs in the form to their initial values automatically.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("TotalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("TotalCost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
$("virusRemoval").value = "";
$("websiteMaking").value = "";
$("computerOptimizationAndSetUp").value = "";
$("TotalCost").value = "";
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotalButton" value="Calculate " onclick="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>

How do I get the sum of radio buttons groups using parameters instead of values

I have multiple sets of radio buttons where the selected values of each set need to be added and displayed to the user. So far I have been changing the values in the function in a switch statement to handle the addition.
<form name="config" id="config">
<div class="row-fluid">
<h3>Memory</h3>
<input type="radio" name="section1" value="4gb" onclick="changePrice(0)" checked>4gb<br>
<input type="radio" name="section1" value="8gb" onclick="changePrice(100)">8gb (+$100)<br>
<input type="radio" name="section1" value="16gb" onclick="changePrice(200)">16gb (+$200)
</div>
<div class="row-fluid">
<h3>Primary Hard Drive</h3>
<input type="radio" name="section2" value="dell" onclick="changePrice(0)" checked>Dell<br>
<input type="radio" name="section2" value="asus" onclick="changePrice(100)">Asus(+$100)
</div>
</form>
<div id="price"></div>
The script I am using right now is
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
function(changePrice){
var val1, val2;
switch(document.config.section1.value){
case "4gb":
val1 = 0;
break;
case "8gb":
val1 = 100;
break;
case "16gb":
val1 = 200;
break;
default:
val1 = 0;
}
switch(document.config.section2.value){
case "dell":
val1 = 0;
break;
case "asus":
val1 = 100;
break;
default:
val1 = 0;
}
var sum = val1 + val2 + baseNum;
displayPrice.innerHTML = sum;
}
Is there a way I can do these calculations using the parameters passed through the changePrice function (so I don't have to change the values in the switch statements)?
Here's how to do this without jQuery.
You'll need to tell the changePrice function which section it should change the price for so you'll need to change the calls to look like this changePrice(1, 100) where 1 is the section and 100 is the price change. Then you can collect all the section prices individually and sum them like so:
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
var sections = {};
function changePrice(section,val){
// add or update the section value
sections[section] = val;
// start with the base price
var sum = baseNum;
// loop over all the sections and add them to the base price
for(var key in sections) {
sum = sections[key] + sum;
}
displayPrice.innerHTML = sum;
}
Here's a jsfiddle
If you change your function definition to the following, it will take in your parameter.
function changePrice(val1)
If you could change your the value attribute on each of your input fields to contain your increment value, it would make the process of calculating your sum much easier. (This may not be appropriate to the problem you are trying to solve.
Basic solution with jQuery
var sum = $("input[name=section1]").val() + $("input[name=section2]").val();
If your list is very long, you could iterate over your radio button sets with jQuery
var sum = 0;
$("input[type=radio]").each(function(){sum += $(this).val();});
<html>
<head>
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.R1.length; i++ ){
if( document.form1.R1[i].checked == true ){
val1 = document.form1.R1[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.R2.length; i++ ){
if(document.form2.R2[i].checked == true ){
val2 = document.form2.R2[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2);
document.getElementById('totalSum').innerHTML=sum;
}
</script>
</head>
<body>
Choose a number:<br>
<form name="form1" id="form1">
<br>
R1 <input id="rdo_1" type="radio" value="5" name="R1" onClick="DisplayPrice(this.value);" checked>5
<br>
R1 <input id="rdo_2" type="radio" value="10" name="R1" onClick="DisplayPrice(this.value);">10
<br>
</form>
Choose another number:<br>
<form name="form2" id="form2">
<br>
R2 <input id="rdo_1" type="radio" value="15" name="R2" onClick="DisplayPrice(this.value);" checked>15
<br>
R2 <input id="rdo_2" type="radio" value="20" name="R2" onClick="DisplayPrice(this.value);">20
<br>
</form>
Your total is Rs = <span name="totalSum" id="totalSum" > 20</span>
</body>
</html>

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;
}

Trying to take which radio button is selected and when is put it through code is returns undefined

Hello I'm new to JavaScript and trying to get a radio button to be registered on variable and then have that variable return another var but it just keeps being returned undefined. If I'm just doing something overtly wrong please tell me.
The radio buttons
Fighter:<input type="radio" id="fig" value="1"/>
Cleric:<input type="radio" id="cleric" value="2"/>
Sorcerer:<input type="radio" id="wiz" value="3"/>
my js
var lvl
var bab
if (document.getElementById('fig').checked) {
var cass = document.getElementById('fig').value;
if (cass == 1){
bab = 1;
}
else if (cass == 2){
bab = 2;
}
else{
bab = 3;
}
}
function show(){
var txtOutput = document.getElementById("txtOutput");
txtOutput.value = bab;
}
And my final place its supposed to be submitting.
<input id="txtOutput">
</input>
Add change event listener for all radio inputs and on change of the input, set the value of the textbox.
Document.querySelectorAll Returns a list of the elements within the document that match the specified group of selectors.
Try this:
var elems = document.querySelectorAll('[name="name"]');
Array.prototype.forEach.call(elems, function(elem) {
elem.addEventListener('change', function() {
document.getElementById("txtOutput").value = this.value;
});
});
Fighter:
<input type="radio" id="fig" value="1" name='name' />Cleric:
<input type="radio" id="cleric" value="2" name='name' />Sorcerer:
<input type="radio" id="wiz" value="3" name='name' />
<br>
<input id="txtOutput">
I think this will give you clarity.
var lvl = "";
var bab = "";
function getValues() {
if (document.getElementById('fig').checked) {
bab = "1 : " + document.getElementById('fig').value + "\n";
}
if (document.getElementById('cleric').checked) {
bab += "2 : " + document.getElementById('cleric').value + "\n";
}
if((document.getElementById('wiz').checked)){
bab += "3 : " + document.getElementById('wiz').value;
}
show();
}
function show(){
var txtOutput = document.getElementById("txtOutput");
txtOutput.innerHTML = bab;
}
/* or you can call it when you click on it */
function consoleIt(obj) {
console.log(obj.id + " : " + obj.value);
}
Fighter : <input type="radio" onclick="consoleIt(this);" id="fig" value="1"/>
Cleric : <input type="radio" onclick="consoleIt(this);" id="cleric" value="2"/>
Sorcerer : <input type="radio" onclick="consoleIt(this);" id="wiz" value="3"/>
<button onclick="getValues();">Get Radio Data</button>
<textarea id="txtOutput"> </textarea>

Categories

Resources