change() jQuery not working - javascript

I'm having some trouble getting my change() event working in jQuery. I am making a small program that converts temperatures to Kelvin, and I want the span that holds my value after conversion to update 1) every time the temperature to convert changes and 2) every time a different temperature scale is selected from the radio buttons.
Relevant Code:
$(document).ready(function() {
$('input[type=radio]').checkboxradio();
var temp = parseFloat()
$('input.listener').change(function() {
var name = $(this).attr("name");
var val = $(this).val();
switch (name) {
case 'unit':
var temperature = $('input#temp').val();
switch (val) {
case 'f':
$('span#output').html(((temperature - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(temperature + 273.15);
break;
case 'r':
$('span#output').html(temperature / 1.8);
break;
}
case 'temp':
var u = $('input[name=unit]:checked').val();
switch (u) {
case 'f':
$('span#output').html(((val - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(val + 273.15);
break;
case 'r':
$('span#output').html(val / 1.8);
break;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
<fieldset>
<legend>Select a Unit to Convert to Kelvin: </legend>
<label for="fRadio">Fahrenheit</label>
<input id="fRadio" class="listener" type="radio" name="unit" value="f">
<label for="cRadio">Celsius</label>
<input id="cRadio" class="listener" type="radio" name="unit" value="c">
<label for="rRadio">Rankine</label>
<input id="rRadio" class="listener" type="radio" name="unit" value="r">
</fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>
<p>
<label>Temperature</label>
<input id="temp" class="listener" type="number" value="32">
</p>
<p>Kelvin: <span id="output"></span></p>
My guess is I'm making a pretty dumb small mistake, but I can't seem to figure it out. Thanks for any and all help, suggestions, and solutions.

Two mistakes with your code:
Forgetting breaks; for the parent switch statement.
Forgetting name="temp" on the temperature field.
I changed the final temperature to a variable and made that the text of the output just so that there would be so many $('span#output').html(temperature);
Also, you should use the oninput event to detect a change for the number field.
$(document).ready(function() {
//$('input[type=radio]').checkboxradio();
var temp = parseFloat();
$('input.listener').on('change', updateTemp);
$('input.listener').on('input', updateTemp);
function updateTemp() {
var name = $(this).attr("name");
var val = $(this).val();
var final;
switch (name) {
case 'unit':
var temperature = $('input#temp').val();
switch (val) {
case 'f':
final = ((temperature - 32) / 1.8) + 273.15;
break;
case 'c':
final = temperature + 273.15;
break;
case 'r':
final = temperature / 1.8;
break;
}
break;
case 'temp':
var u = $('input[name=unit]:checked').val();
switch (u) {
case 'f':
final = ((val - 32) / 1.8) + 273.15;
break;
case 'c':
final = val + 273.15;
break;
case 'r':
final = val / 1.8;
break;
}
break;
}
$("#output").text(final);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget">
<fieldset>
<legend>Select a Unit to Convert to Kelvin: </legend>
<label for="fRadio">Fahrenheit</label>
<input id="fRadio" class="listener" type="radio" name="unit" value="f">
<label for="cRadio">Celsius</label>
<input id="cRadio" class="listener" type="radio" name="unit" value="c">
<label for="rRadio">Rankine</label>
<input id="rRadio" class="listener" type="radio" name="unit" value="r">
</fieldset>
</div>
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert the value to Kelvin:</p>
<p>
<label>Temperature</label>
<input id="temp" class="listener" type="number" name="temp" value="32">
</p>
<p>Kelvin: <span id="output"></span></p>

You should set one of the radio buttons as default with checked="checked". Then try following:
$(document).ready(function () {
$('input.listener').change(function () {
if ($(this).attr("type") == 'radio') {
//radio button changed
var u = $(this).val();
} else {
var u = $("input[type='radio']:checked").val();
}
var temperature = $('#temp').val();
switch (u) {
case 'f':
$('span#output').html(((temperature - 32) / 1.8) + 273.15);
break;
case 'c':
$('span#output').html(temperature + 273.15);
break;
case 'r':
$('span#output').html(temperature / 1.8);
break;
}
});
});

You do not have break; after
case 'unit':
and when var name = "temp"
var val = $(this).val();
the value of var val above would be a number in string format, so when you do val + something in case 'temp' the number is getting appended instead getting added or substracted. Use parseInt(val) to convert the value of input box to integer in case of 'temp'.

Related

JavaScript calculator just returns "NaN"

I'm making a calculator for a game I play and whenever I run it, it just returns "NaN" for two values, only one of the values actually returns as it should. The two values that return NaN are the ones that run through switch statements and I found that the values you get from the switch statements are undefined so I think that's where it goes wrong. I tried looking for other questions like this on StackOverflow and I found some but their answers didn't work for me.
var iron_cost = 0
var string_cost = 0
var spider_e_cost = 0
var tami_1_amount = 0
var tami_2_amount = 0
var tami_1_tier = 0
var tami_2_tier = 0
var ta_per_min_1 = 0
var ta_per_min_2 = 0
var cpt_tpc = 0
var cph_tpc = 0
var cpd_tpc = 0
function calculate_tpc() {
var string_cost = document.getElementById("string_tpc").value;
var spider_e_cost = document.getElementById("spider_eye_tpc").value;
var iron_cost = document.getElementById("iron_tpc").value;
var tami_1_tier = document.getElementById("minions_tier_1_tpc").value;
var tami_2_tier = document.getElementById("minions_tier_2_tpc").value;
var tami_1_amount = document.getElementById("minions_1_tpc").value;
var tami_2_amount = document.getElementById("minions_2_tpc").value;
var step1 = string_cost * 3.16;
var step2 = iron_cost * 0.2;
var step3 = step1 + step2 + spider_e_cost;
switch (tami_1_tier) {
case 1:
var ta_per_min_1 = 2;
break;
case 2:
var ta_per_min_1 = 2;
break;
case 3:
var ta_per_min_1 = 2.3;
break;
case 4:
var ta_per_min_1 = 2.3;
break;
case 5:
var ta_per_min_1 = 2.6;
break;
case 6:
var ta_per_min_1 = 2.6;
break;
case 7:
var ta_per_min_1 = 3.15;
break;
case 8:
var ta_per_min_1 = 3.15;
break;
case 9:
var ta_per_min_1 = 4.1;
break;
case 10:
var ta_per_min_1 = 4.1;
break;
case 11:
var ta_per_min_1 = 6;
break;
}
switch (tami_2_tier) {
case 1:
var ta_per_min_2 = 2;
break;
case 2:
var ta_per_min_2 = 2;
break;
case 3:
var ta_per_min_2 = 2.3;
break;
case 4:
var ta_per_min_2 = 2.3;
break;
case 5:
var ta_per_min_2 = 2.6;
break;
case 6:
var ta_per_min_2 = 2.6;
break;
case 7:
var ta_per_min_2 = 3.15;
break;
case 8:
var ta_per_min_2 = 3.15;
break;
case 9:
var ta_per_min_2 = 4.1;
break;
case 10:
var ta_per_min_2 = 4.1;
break;
case 11:
var ta_per_min_2 = 6;
break;
}
var step4 = ta_per_min_1 * tami_1_amount;
var step5 = ta_per_min_2 * tami_2_amount;
var step6 = step4 + step5;
var step7 = step6 * step3;
var step8 = step7 * 60;
var step9 = step8 * 24;
document.getElementById("cpt_tpc").innerHTML = step3;
document.getElementById("cph_tpc").innerHTML = step8;
document.getElementById("cpd_tpc").innerHTML = step9;
document.getElementById("test1").innerHTML = ta_per_min_1;
document.getElementById("test2").innerHTML = ta_per_min_2;
}
html,
body {
text-align: center;
}
;
<html>
<head>
<link rel="stylesheet" type="text/css" href="interface.css" />
<body>
<h1>Calculator</h1>
<br /> String Price: <input type="text" id="string_tpc" value="0">
<br /> Spider Eye Price: <input type="text" id="spider_eye_tpc" value="0">
<br /> Iron Price: <input type="text" id="iron_tpc" value="0">
<br /> Minions Tier 1: <input type="text" id="minions_tier_1_tpc" value="0"> Minion Amount 1: <input type="text" id="minions_1_tpc" value="0">
<br /> Minions Tier 2: <input type="text" id="minions_tier_2_tpc" value="0"> Minion Amount 2: <input type="text" id="minions_2_tpc" value="0">
<br />
<button onclick="calculate_tpc()">Calculate</button>
<br /> Current Coins per Tarantula: <span id="cpt_tpc">0</span>
<br /> Coins per hour: <span id="cph_tpc">0</span>
<br /> Coins per day: <span id="cpd_tpc">0</span>
<script type="text/javascript" src="main.js"></script>
</body>
</head>
</html>
The main problem is to use strings from input. The further effect is to get no values from the switch statements, because the value is a string and in all cases, you have numbers. The comparison is here strict, like ===.
For unknown values, you could return the function and omit calculation with not given values.
'use strict';
function calculate_tpc() {
var string_cost = +document.getElementById("string_tpc").value;
var spider_e_cost = +document.getElementById("spider_eye_tpc").value;
var iron_cost = +document.getElementById("iron_tpc").value;
var tami_1_tier = +document.getElementById("minions_tier_1_tpc").value;
var tami_2_tier = +document.getElementById("minions_tier_2_tpc").value;
var tami_1_amount = +document.getElementById("minions_1_tpc").value;
var tami_2_amount = +document.getElementById("minions_2_tpc").value;
var step1 = string_cost * 3.16;
var step2 = iron_cost * 0.2;
var step3 = step1 + step2 + spider_e_cost,
ta_per_min_1,
ta_per_min_2;
switch (tami_1_tier) {
case 1:
case 2:
ta_per_min_1 = 2;
break;
case 3:
case 4:
ta_per_min_1 = 2.3;
break;
case 5:
case 6:
ta_per_min_1 = 2.6;
break;
case 7:
case 8:
ta_per_min_1 = 3.15;
break;
case 9:
case 10:
ta_per_min_1 = 4.1;
break;
case 11:
ta_per_min_1 = 6;
break;
default: return;
}
switch (tami_2_tier) {
case 1:
case 2:
ta_per_min_2 = 2;
break;
case 3:
case 4:
ta_per_min_2 = 2.3;
break;
case 5:
case 6:
ta_per_min_2 = 2.6;
break;
case 7:
case 8:
ta_per_min_2 = 3.15;
break;
case 9:
case 10:
ta_per_min_2 = 4.1;
break;
case 11:
ta_per_min_2 = 6;
break;
default: return;
}
var step4 = ta_per_min_1 * tami_1_amount;
var step5 = ta_per_min_2 * tami_2_amount;
var step6 = step4 + step5;
var step7 = step6 * step3;
var step8 = step7 * 60;
var step9 = step8 * 24;
document.getElementById("cpt_tpc").innerHTML = step3;
document.getElementById("cph_tpc").innerHTML = step8;
document.getElementById("cpd_tpc").innerHTML = step9;
//document.getElementById("test1").innerHTML = ta_per_min_1;
//document.getElementById("test2").innerHTML = ta_per_min_2;
}
<h1>Calculator</h1>
<br /> String Price: <input type="text" id="string_tpc" value="0">
<br /> Spider Eye Price: <input type="text" id="spider_eye_tpc" value="0">
<br /> Iron Price: <input type="text" id="iron_tpc" value="0">
<br /> Minions Tier 1: <input type="text" id="minions_tier_1_tpc" value="0"> Minion Amount 1: <input type="text" id="minions_1_tpc" value="0">
<br /> Minions Tier 2: <input type="text" id="minions_tier_2_tpc" value="0"> Minion Amount 2: <input type="text" id="minions_2_tpc" value="0">
<br />
<button onclick="calculate_tpc()">Calculate</button>
<br /> Current Coins per Tarantula: <span id="cpt_tpc">0</span>
<br /> Coins per hour: <span id="cph_tpc">0</span>
<br /> Coins per day: <span id="cpd_tpc">0</span>

(JS) Using IF/Switch statements to change slider value

Still getting the hang of Javascript so forgive me if this seems like basic stuff.
I've set up a slider on a web page and the CSS/HTML function perfectly but I'm trying to display a year value to correspond with each value of the slider from 1 to 6.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = 133;
slider.oninput = function() {
switch (this.value) {
case 1:
output.innerHTML = 133;
break;
case 2:
output.innerHTML = 88;
break;
case 3:
output.innerHTML = 60;
break;
case 4:
output.innerHTML = 44;
break;
case 5:
output.innerHTML = 36;
break;
case 6:
output.innerHTML = 26;
break;
default:
output.innerHTML = 133;
}
output.innerHTML = this.value;
}
<div class="slidecontainer">
<input type="range" min="1" max="6" value="1" class="slider" id="myRange">
<p><span id="demo"></span> BC</p>
</div>
Currently it outputs 1 to 6 so it does function and I can set the default value to 133 before input, it just doesn't push out the values I need once the slider is moved.
Is a switch statement the correct tool for this job and, if so, where have I gone wrong?
this.value returns a string. You need to make it return a number in order for your comparison to work. Or compare against strings. Either way, the below example works. Look how I added parseInt(this.value) inside your switch operator.
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = 133;
slider.oninput = function() {
switch (parseInt(this.value)) {
case 1:
output.innerHTML = 133;
break;
case 2:
output.innerHTML = 88;
break;
case 3:
output.innerHTML = 60;
break;
case 4:
output.innerHTML = 44;
break;
case 5:
output.innerHTML = 36;
break;
case 6:
output.innerHTML = 26;
break;
default:
output.innerHTML = 133;
}
}
<div class="slidecontainer">
<input type="range" min="1" max="6" value="1" class="slider" id="myRange">
<p><span id="demo"></span> BC</p>
</div>

Restrict input field

How to I restrict a number entering into input field (numeric) greater than another number using JavaScript?
I used:
function numberalert(e) {
var matrictotal = document.getElementById("matrictotal").value;
var matricobtained = document.getElementById("matricobtained").value;
var intertotal = document.getElementById("intertotal").value;
var interobtained = document.getElementById("interobtained").value;
var bachelortotal = document.getElementById("bachelortotal").value;
var bachelorobtained = document.getElementById("bachelorobtained").value;
var mphilltotal = document.getElementById("mphilltotal").value;
var mphillobtained = document.getElementById("mphillobtained").value;
if (matricobtained > matrictotal || interobtained > intertotal || bachelorobtained > bachelortotal || mphillobtained > mphilltotal) {
alert("pleses provide obtained marks less then total marks");
e.returnValue = false;
e.preventDefault();
} else {
return true;
}
}
But after alert it allows number place in input field.
First, just get the object that represents each object then pass in the two methods into a helped method to do the actual comparison. If the values are not what you are looking for, then set the objects value to "" and highlight the textbox to show which one is wrong.
function numberalert(e) {
var matrictotal = document.getElementById("matrictotal");
var matricobtained = document.getElementById("matricobtained");
var intertotal = document.getElementById("intertotal");
var interobtained = document.getElementById("interobtained");
var bachelortotal = document.getElementById("bachelortotal");
var bachelorobtained = document.getElementById("bachelorobtained");
var mphilltotal = document.getElementById("mphilltotal");
var mphillobtained = document.getElementById("mphillobtained");
checkValue(matrictotal, matricobtained);
checkValue(intertotal, interobtained);
checkValue(bachelortotal, bachelorobtained);
checkValue(mphilltotal, mphillobtained);
}
function checkValue(total, obtained){
if (obtained.value > total.value) {
alert("Please provide obtained marks less then total marks: " + obtained.id);
obtained.value = "";
obtained.classList.add("error");
} else {
obtained.classList.remove("error");
return true;
}
}
.error {
border: 2px solid #FF0000;
}
<label for="matrictotal">matrictotal</label>
<input type="text" id="matrictotal" value="10">
<label for="matricobtained">matricobtained</label>
<input type="text" id="matricobtained" value="10">
<br />
<label for="intertotal">intertotal</label>
<input type="text" id="intertotal" value="10">
<label for="interobtained">interobtained</label>
<input type="text" id="interobtained" value="10">
<br />
<label for="bachelortotal">bachelortotal</label>
<input type="text" id="bachelortotal" value="10">
<label for="bachelorobtained">bachelorobtained</label>
<input type="text" id="bachelorobtained" value="10">
<br />
<label for="mphilltotal">mphilltotal</label>
<input type="text" id="mphilltotal" value="10">
<label for="mphillobtained">mphillobtained</label>
<input type="text" id="mphillobtained" value="10">
<button onclick=numberalert(this)>Check values</button>
Note : In Javascript there is no strictly greater than or strictly less than comparator .
In case if you need strictly greater than use
(a !==b && a > b) (or) (!(a < b))
Similarly for strictly less than use
(a !== b && a < b) (or) (!(a>b))
var toCheckNumber = 100;
validate = function(el, event) {
var errorText = document.getElementById('errorText');
errorText.innerHTML = "";
var x = event.which;
var value = el.value;
var number = 0;
switch (x) {
case 48: number =0;break;
case 49: number = 1; break;
case 50: number = 2; break;
case 51: number = 3; break;
case 52: number = 4; break;
case 53: number = 5; break;
case 54: number = 6; break;
case 55: number = 7; break;
case 56: number = 8; break;
case 57: number = 9; break;
case 8: number = -1; break;
case 46: number = -1; break;
default : event.preventDefault(); return ;
}
var tempval = (number !== -1) ? value * 10 + number : value;
if (!(tempval < toCheckNumber)) {
event.preventDefault();
errorText.innerHTML = "Enter number less than " + toCheckNumber;
}
}
<input type="number" onkeydown="validate(this,event)" onchange="document.getElementById('errorText').innerHTML=''">
<div id="errorText" style="color:red"></div>

Null value for check box - Switch Statement

I have basic form with input text boxes and a checkboxes. The example currently shows two items. I am trying to use a switch case to determine what was checked and then calculate a total based on the quantity and user selection. I am getting an error inside the switch case for mufin1.checked == true. How can get the proper value to be returned? JSFIDDLE
JS
function charge(){
var q_muffin1 = document.getElementById('muffin_quantity1');
var muffin1 = document.getElementById('muffin1');
var q_muffin2 = document.getElementById('muffin_quantity2');
var muffin2 = document.getElementById('muffin2');
var charge;
var form = document.getElementById("muffinOrder");
var checkbox = form.getElementsByTagName("checkbox");
switch (checkbox.checked) {
case (mufin1.checked == true):
charge += q_muffin1 * muffin1;
break;
case (mufin2.checked == true):
charge += q_muffin2 * muffin2;
break;
default:
window.alert("Sorry, we are out of");
}
window.alert("Your total is: $" + charge);
return false;
}
html
<form action="" id="muffinOrder" onsubmit="return charge()">
Quantity: <input type="text" name="muffin_quantity1" id="muffin_quantity1"><input type="checkbox" name="muffin1" id="muffin1" value=".59">Blueberry Muffin .59¢<br />
Quantity: <input type="text" name="muffin_quantity2" id="muffin_quantity2"><input type="checkbox" name="muffin2" id="muffin2" value=".69">Banana Nutted Muffin .90¢<br />
<input type="submit" value="Submit" >
</form>
Assuming you don't want to handle the case where both checkboxes are checked, you could write it like this :
switch (true) {
case (mufin1.checked):
charge += q_muffin1 * muffin1;
break;
case (mufin2.checked):
charge += q_muffin2 * muffin2;
break;
default:
window.alert("Sorry, we are out of");
}
But your whole code would probably be cleaner without those variables xxx1 and xx2. I'm not sure of the whole goal but this could be something like that :
var charge = 0;
[1,2].forEach(function(id){
var muffin = document.getElementById('muffin'+id);
var q_muffin = document.getElementById('muffin_quantity'+id).value;
if (muffin.checked) charge += q_muffin;
});
window.alert("Your total is: $" + charge);
string str=Convert.toString(checkbox.checked);//int return With Null Value in ""
switch (str.toUpper()) {
case "TRUE":
charge += q_muffin1 * muffin1;
break;
case "FALSE":
charge += q_muffin2 * muffin2;
break;
default:
window.alert("Sorry, we are out of");
}
window.alert("Your total is: $" + charge);
CHECK This

Using radio buttons for a calculator

I am trying to make a simple calculator using radio buttons to select addition, subtraction, multiplication or division. However it is not working. I have tried a lot of things and googled it a lot, but I can't find out the issue. If anyone finds a problem with what I have, could you please give me a solution. Thanks!
<html>
<head>
<script language="javascript">
function operation() {
var ans =document.getElementById("answer").value;
if (document.getElementById("add").value = "add") {
ans= calculate(add);
}
if (document.getElementById("subtract").value = "subtract") {
ans= calculate(subtract);
}
if (document.getElementById("multiply").value = "multiply") {
ans= calculate(multiply);
}
if (document.getElementById("divide").value = "divide") {
ans= calculate(divide);
}
}
function calculate(action){
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
var result;
switch(action){
case add:
result= parseInt(num1)+parseInt(num2);
break;
case subtract:
result= num1-num2;
break;
case multiply:
result= num1*num2;
break;
case divide:
result= num1/num2;
break;
}
return result;
</script>
<title>
Calculator
</title>
</head>
<body>
<form>
<input type="text" id="num1">
+<input type="radio" name="group1" id="add" value="add">
-<input type="radio" name="group1" id="subtract" value="subtract">
*<input type="radio" name="group1" id="multiply" value="multiply">
/<input type="radio" name="group1" id="divide" value="divide">
<input type="text" id="num2">
=
<input type="text" id="answer" readonly>
<input type="button" value="Calculate" onClick="calculate()">
</form>
</body>
</html>
Your calculate function takes an argument:
function calculate(action){}
You are calling it without passing any paremeters:
<input type="button" value="Calculate" onClick="calculate()">
actually, i made this FIDDLE as the answer for someone's question few days ago. Is this some sort of homework?
function operation() {
var ans =document.getElementById("answer");
if (document.getElementById("add").checked) {
ans.value= calculate('add');
}
if (document.getElementById("subtract").checked) {
ans.value= calculate('subtract');
}
if (document.getElementById("multiply").checked) {
ans.value= calculate('multiply');
}
if (document.getElementById("divide").checked) {
ans.value= calculate('divide');
}
}
function calculate(action){
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
var result;
switch(action){
case 'add':
result= parseInt(num1)+parseInt(num2);
break;
case 'subtract':
result= num1-num2;
break;
case 'multiply':
result= num1*num2;
break;
case 'divide':
result= num1/num2;
break;
}
return result;
}
fiddle
You're not putting the result back into the answer box. You can return the value, but you have to tell it what text element to use.
document.getElementById("answer").value = ans;
In your if statements... "=" means assignment. "==" is comparison.
You have set the "value" of each radio button to something. So, you're checking if the value for "add" is "add", but you have already explicitly set the value to "add". Radio buttons are boolean: true or false.
function op() {
var ans = 0;
if (document.getElementById("add").value) {
ans= calculate(add);
} else if (document.getElementById("subtract").value) {
ans= calculate(subtract);
} else if (document.getElementById("multiply").value) {
ans= calculate(multiply);
} else if (document.getElementById("divide").value) {
ans= calculate(divide);
}
document.getElementById("answer").value = ans;
}
function calculate(action){
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
var result;
switch(action){
case add:
result= parseInt(num1)+parseInt(num2);
break;
case subtract:
result= num1-num2;
break;
case multiply:
result= num1*num2;
break;
case divide:
result= num1/num2;
break;
}
return result;
}
<input type="button" value="Calculate" id="b" onclick="op();">
You are looking at the values of buttons to see if they are active. They will always have the value that is assigned to them whether they are checked or not.
if (document.getElementById("add").value = "add") {
...when you should be checking to see if they're checked.
if (document.getElementById("add").getAttribute("checked") == "checked") {
Also, in JavaScript "==" is used for comparison, "=" is used to assign a value.

Categories