Javascript value does not change when alternative radio button is clicked - javascript

Im learning JavaScript....slowly. Im working front end for a friend and learning as I go along. I thought JavaScript would be a better starting point than Jquery so please keep that in mind when answering, unless I am wrong assuming the above.
My problem is as follows
When looking at above image you can see the estimated return has been correctly calculated for the low risk option selected.
However if user clicks High Risk radio button without moving slider and then clicks the get estimate button. the amount does not update...?
Only when user moves slider the amount will update according to radio button selected. But if radio button is changed without moving slider the amount DOES NOT UPDATE. Hope this makes sense? If not please let me know and ill be happy to clarify.
Code as follows:
Radio Buttons (shortened version)
<input type="radio" id="control_01" name="risk" value="1" checked>
<input type="radio" id="control_02" name="risk" value="2">
<input type="radio" id="control_03" name="risk" value="3">
Javascript
function getReturn() {
var risk = document.forms[0];
var slideAmount = document.getElementById("slideAmount").value;
var txt;
var returns;
var i;
for (i = 0; i < risk.length; i++) {
if (risk[i].checked) {
txt = risk[i].value;
} //for
if (txt = 1) {
returns = slideAmount * 0.06;
returns = Math.ceil(returns); // NO decimals
}
if (txt = 2) {
returns = slideAmount * 0.11;
returns = Math.ceil(returns); // NO decimals
}
if (txt = 3) {
returns = slideAmount * 0.17;
returns = Math.ceil(returns); // NO decimals
}
} //for
document.getElementById("returns").innerHTML = "ESTIMATED RETURN PA: <span style='color:red'><i class='fa fa-usd fa-lg'></i>" + returns + "</span>";
}
HTML Button on Click
<button type="button" class="btn btn-primary btn-lrg" onclick="getReturn()">GET ESTIMATE</button>
<div id="returns" style="font-weight: 800; color:black; font-size: 15px">Estimated</div>
Any advice, help and tips appreciated.

txt = 1 is not a comparison, it is an assignment. It has to be txt == 1, ... . The way you wrote it txt = 3 will always be true, because 3 is truthy.
In general you should use a linter like eslint or a code styleguide guideline tool like standardjs, those tools warn you about these common mistakes and pitfalls.
Beside that, you should write this kind of if clauses that way:
if (txt == 1) {
returns = slideAmount * 0.06;
returns = Math.ceil(returns); // NO decimals
} else if (txt == 2) {
returns = slideAmount * 0.11;
returns = Math.ceil(returns); // NO decimals
} else if (txt == 3) {
returns = slideAmount * 0.17;
returns = Math.ceil(returns); // NO decimals
}
And if possible use === instead of ==.
if (risk[i].checked) {
txt = Number(risk[i].value); // convert the value to a Number
} //for
if (txt === 1) {
returns = slideAmount * 0.06;
returns = Math.ceil(returns); // NO decimals
} else if (txt === 2) {
returns = slideAmount * 0.11;
returns = Math.ceil(returns); // NO decimals
} else if (txt === 3) {
returns = slideAmount * 0.17;
returns = Math.ceil(returns); // NO decimals
}

Solution is just not to correct your mistake, but also to reduce the number of line of code.
function getReturn() {
var risk = document.forms[0];
var slideAmount = document.getElementById("slideAmount").value;
var txt;
var returns;
for (var i = 0; i < risk.length; i++) {
if (risk[i].checked) {
txt = risk[i].value;
} //for
if (txt == 1) {
returns = slideAmount * 0.06;
} else if (txt == 2) {
returns = slideAmount * 0.11;
} else if (txt == 3) {
returns = slideAmount * 0.17;
}
} //for
document.getElementById("returns").innerHTML = "ESTIMATED RETURN PA: <span style='color:red'><i class='fa fa-usd fa-lg'></i>" + Math.ceil(returns) + "</span>";
}
= is an assignment operator, whereas == is a comparison operator.
Hope this will help you.

There are several issues with the code.
You should exit your for loop when the radio button has been found
As mentioned in several posts, = should be replaced with == in your comparators.
You have incomplete HTML leaving those offering help to make assumptions about your DOM elements. For example, <form> and <input type="range"> are missing from the example.
Below please find a sample with missing DOM elements added and simplified logic. A switch/case was used as an example because some find this easier to read. It is otherwise logically equivalent to the if/else examples.
<html>
<form>
<input type="radio" id="control_01" name="risk" value="1" checked>
<input type="radio" id="control_02" name="risk" value="2">
<input type="radio" id="control_03" name="risk" value="3">
</form>
<button type="button" class="btn btn-primary btn-lrg" onclick="getReturn()">GET ESTIMATE</button>
<div id="returns" style="font-weight: 800; color:black; font-size: 15px">Estimated</div>
<input type="range" id="slideAmount" value="1" max="100"></input>
<script>
function getReturn() {
var risk = document.forms[0];
var slideAmount = document.getElementById("slideAmount").value;
var returns;
for (var i = 0; i < risk.length; i++) {
// Skip unchecked radio buttons
if (!risk[i].checked) {
continue;
}
// Divide by one to force string to value
switch(risk[i].value/1) {
case 1:
returns = Math.ceil(slideAmount * 0.06);
break;
case 2:
returns = Math.ceil(slideAmount * 0.11);
break;
case 3:
returns = Math.ceil(slideAmount * 0.17);
break;
default:
console.error("Shouldn't have reached " + risk[i].value);
}
}
document.getElementById("returns").innerHTML = "ESTIMATED RETURN PA: <span style='color:red'><i class='fa fa-usd fa-lg'></i>" + returns + "</span>";
}
</script>
</html>

Hi please do these changes in function:
function getReturn() {
var risk = document.getElementsByName('risk'); // change
var slideAmount = document.getElementById("slideAmount").value;
var txt;
var returns;
var i;
for (i = 0; i < risk.length; i++) {
if (risk[i].checked) {
txt = risk[i].value;
} //for
if (txt === "1") { // change
returns = slideAmount * 0.06;
returns = Math.ceil(returns); // NO decimals
}
if (txt === "2") { // change
returns = slideAmount * 0.11;
returns = Math.ceil(returns); // NO decimals
}
if (txt === "3") { // change
returns = slideAmount * 0.17;
returns = Math.ceil(returns); // NO decimals
}
} //for
document.getElementById("returns").innerHTML = "ESTIMATED RETURN PA: <span style='color:red'><i class='fa fa-usd fa-lg'></i>" + returns + "</span>";
}

Related

How to remove innerHTML value to be shown initially

I am trying to create a multiplication table in JavaScript. The user is prompted to provide the Table number (1 to 10) after which all the question marks ('?') are replaced with that number. The user then needs to enter the answers in all the provided text fields. Finally, the user will have the option to check the answer (i.e. whether it is right or wrong).
When I run my code. After entering the user data to prompt it shows Incorrect infront of each textfield and the user entered value just before the Check answers button. How can I remove them to be shown initially.
Output:
My code:
function result() {
var value = document.getElementById("a1").value;
var checkMessageSpan1 = document.getElementById("checkMessage1");
var checkMessageSpan2 = document.getElementById("checkMessage2");
var r = x * 1;
if (value == x) {
checkMessageSpan1.innerHTML = "<span style=\"color:green\">"+"Correct!";
}else{
checkMessageSpan1.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
}
var value = document.getElementById("a2").value;
var r = x * 2;
if (value == r) {
checkMessageSpan2.innerHTML = "<span style=\"color:green\">"+"Correct!";
}else{
checkMessageSpan2.innerHTML = "<span style=\"color:red\">"+"Incorrect!";
}
</script>
<button onClick="alert_field()"> Generate Question</button><br><br>
<p id="s1">
? x 1 = <input type="text" id="a1"><span id="checkMessage1"></span><br>
? x 2 = <input type="text" id="a2"><span id="checkMessage2"></span><br>
</p><br><br>
<p id="a"></p>
Check answers
For replacing all special characters, you may leverage regular expressions in js
var res=str.replace(/[^a-zA-Z0-9]/g,x); instead of
var res = str.replace("?",x);
More on Regular expressions in JS https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Try to add this code:
var value = document.getElementById("a1").value;
if (checkMessageSpan1.style.display === "none") {
checkMessageSpan1.style.display = "inline-block";
} else {
checkMessageSpan1.style.display = "none";
}
var value = document.getElementById("a2").value;
if (checkMessageSpan2.style.display === "none") {
checkMessageSpan2.style.display = "inline-block";
} else {
checkMessageSpan2.style.display = "none";
}

Using both Onkeyup and Onchange

I have two input boxes, one takes user input and multiplies it with 596 and then displays the result in the second input box while updating a <span> with the check if its PlanA or PlanB
function calculate() {
var ethBox = document.getElementById('eth').value;
var myResult = ethBox * 596;
document.getElementById('usd').value = myResult.toFixed(2);
if(ethBox < 10){
document.getElementById('span').innerHTML ="PlanA";
}else if(ethBox >= 11 && ethBox <=20){
document.getElementById('span').innerHTML ="PlanB";
}
}
it work.
But I also want the user input in the second input box to be divided by 596 and display the result in the first input box, also updating the <span> with the conditional statement at the same time
function reverse() {
var usdBox = document.getElementById('usd').value;
var myResult = usdBox / 596;
document.getElementById('eth').value = myResult.toFixed(2);
}
This code changes the value of the first input box but it doesnt update the <span>
Input Boxes
<input id="eth" onkeyup="calculate();" type="text">
<input id="usd" onkeyup="reverse();" type="text">
The Span
<span id="span"></span>
I also tried using onkeyup and onchange for the first input box, which didn't work
You need to add the following code in reverse function also. Added a common() method to do the task that is common to both methods.
var ethBox = document.getElementById('eth').value;
if(parseInt(ethBox,10) < 10){
document.getElementById('span').innerHTML ="PlanA";
}else if(ethBox >= 11 && ethBox <=20){
document.getElementById('span').innerHTML ="PlanB";
}
<script>
function calculate() {
var ethBox = document.getElementById('eth').value;
var myResult = ethBox * 596;
document.getElementById('usd').value = myResult.toFixed(2);
common();
}
function reverse() {
var usdBox = document.getElementById('usd').value;
var myResult = usdBox / 596;
document.getElementById('eth').value = myResult.toFixed(2);
common();
}
function common() {
var ethBox = document.getElementById('eth').value;
if(parseInt(ethBox,10) < 10){
document.getElementById('span').innerHTML ="PlanA";
}else if(ethBox >= 11 && ethBox <=20){
document.getElementById('span').innerHTML ="PlanB";
}
}
</script>
<input id="eth" onkeyup="calculate();" type="text">
<input id="usd" onkeyup="reverse();" type="text">
<span id="span"></span>

javascript numbers from HTML Textbox

I have 2 HTML textboxes and need to convert them to numbers so I can perform a calculation but I am just getting NaaN. My code is:
Where totalcost is html textbox
and pg is also a html textbox
document.getElementById("totalcost").value = parseFloat(document.getElementById("pg").value) + parseFloat(document.getElementById("totalcost").value);
I want the totalcost box to be populated by "totalcost + pg" as it is a click and add cart system. Why Float, its for bitcoin.
Try this:
// get the `pg` value and attempt to convert to a Number, otherwise default to 0.00
var pg = Number(document.getElementById("pg").value) || 0.00;
// get the `totalcost` value and attempt to convert to a Number, otherwise default to 0.00
var totalCost = Number(document.getElementById("totalcost").value) || 0.00;
// update the `totalcost` element to include the sum of `pg` and `totalcost`
document.getElementById("totalcost").value = pg + totalCost
Added some comments to help explain each step.
Lets do that:
function isNumeric(n) {
/* http://stackoverflow.com/a/1830844/603774 */
return !isNaN(parseFloat(n)) && isFinite(n);
}
function calc() {
var
d_1 = document.getElementById('d_1').value,
d_2 = document.getElementById('d_2').value,
result;
/* Validation for d_1 */
if (!isNumeric(d_1)) {
alert('d_1 is not a number');
return;
}
/* Validation for d_2 */
if (!isNumeric(d_2)) {
alert('d_2 is not a number');
return;
}
result = +d_1 + +d_2;
alert('Result: ' + result);
}
<input type="text" id="d_1"> + <input type="text" id="d_2"> <input type="button" value="calculate" onclick='calc()'>
Use the unary plus operator with or conditional
document.getElementById("totalcost").value = (+(document.getElementById("pg").value) || 0) + (+(document.getElementById("totalcost").value) || 0);

Don't run function if field empty

I'm new here, and very new to Javascript and programming concepts in general. Part of the form I'm working on simlpy needs to calculate the difference between two prices. I do know float numbers are screwy, so I have that part figured out. And it calculates, and inputs it into field 3. The only thing I can't seem to figure out is making it so that if either field 1 or 2 is empty, the function doesn't run. It should only run when both fields are filled. Here's my example code:
<input type="text" id="1"> </input><br/>
<input type="text" id="2"> </input><br/>
<input type="text" id="3"> </input><br/>
<br/><br/><br/>
<p id="test"></p>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
function emptyCheck(){
if ($("#1") = ""){
$("#3").val("");
}
else if ($("#2") = ""){
$("#3").val("");
}
else{
rateDiff();
}
}
function rateDiff(){
var clientRate = $("#1").val() * 100;
var agentRate = $("#2").val() * 100;
var fareDiff = clientRate - agentRate;
var fareDiffDec = fareDiff / 100;
$("#3").val(fareDiffDec.toFixed(2));
}
$("#1").keyup(emptyCheck);
$("#2").keyup(emptyCheck);
</script>
I don't get what I'm doing wrong here. Can anyone point me in the right direction?
if ($("#1") = ""){
should be
if ($("#1").val() == ""){
same for $("#2") = ""
$("#1") is a jquery element, not the value.
Also you put = instead of ==
$("#1") = "")
Should be
$("#1").val() == "")
One = is used to assign a value, while two == is to do a comparison.
Just use the "falsey" of JavaScript and the values:
function emptyCheck(){
if (!$("#1").val() || !$("#2").val()){
$("#3").val("");
}
else{
rateDiff();
}
}
NOTE: you would be better parsing the numbers to handle alpha entry:
function emptyCheck() {
if (!parseFloat($("#1").val()) || !parseFloat($("#2").val())) {
$("#3").val("");
} else {
rateDiff();
}
}
function rateDiff() {
var clientRate = parseFloat($("#1").val()) * 100;
var agentRate = parseFloat($("#2").val()) * 100;
var fareDiff = clientRate - agentRate;
var fareDiffDec = fareDiff / 100;
$("#3").val(fareDiffDec.toFixed(2));
}
$("#1").keyup(emptyCheck);
$("#2").keyup(emptyCheck);

Celsius and Fahrenheit Converter- JavaScript

I want to make a webpage that has two text boxes, a Celsius and Fahrenheit box. In between them, there is a convert button which converts Celsius to Fahrenheit and Fahrenheit to Celsius. If there is letters in either box, I want to cancel the converting and an alert pop up saying "Only numbers please!" So far, I haven't figured out how to get the alert and when I type numbers in the Celsius box, it always says the number -18 in the same box. Fahrenheit is fine.
HTML:
<html>
<head>
<title>Temparature Converter</title>
<script type="text/javascript" src="tempconversion.js"></script>
</head>
<body>
Celsius: <input id="c" onkeyup="convert('C')">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
Fahrenheit: <input id="f" onkeyup="convert('F')">
</body>
</html>
JavaScript:
function convertTemp(degree) {
if (degree == "C") {
F = document.getElementById("c").value * 9 / 5 + 32;
document.getElementById("f").value = Math.round(F);
} else {
C = (document.getElementById("f").value -32) * 5 / 9;
document.getElementById("c").value = Math.round(C);
}
}
Note: I got some code from W3Schools so I think the onkeyup convert is a little funny. If possible, please notify me how it has to change as well as the JavaScript.
There is no need for the onkeyup attributes, since they original code from W3Schools was designed to instantly update values as they were entered.
I did modify the functionality to clear of original value, that way the conversion button can work both ways with a simple code.
Here's a quick JavaScript to do the job:
function convertTemp() {
// Set the initial variables for c (Celsius) and f (Fahrenheit)
var c = document.getElementById('c'), f = document.getElementById('f');
// Test if there is a value for Celsius
if(c.value != '') {
// Set the value for Fahrenheit
f.value = Math.round(c.value * 9 / 5 + 32);
// Clear the value for Celsius
c.value = '';
// If there isn't a value for Celsius
} else {
// Set the value for Celsius
c.value = Math.round((f.value - 32) * 5 / 9);
// Clear the value for Fahrenheit
f.value = '';
}
}
And its accompanying HTML:
Celcius:<input id="c">
Fahrenheit:<input id="f">
<button type="button" id="convert" onclick="convertTemp()">Convert</button>
It can be tested at: http://jsfiddle.net/bhz6uz54/
Something to remember about simple code, like this, there is nothing to verify the supplied values are acceptable. A little regex can act as validation, but how it would be implemented depends on how you want to flag the problem.
I personally hate Do-it Buttons so I'd go with a more dynamic solution:
// Get the Input elements:
var $f = document.getElementById("f");
var $c = document.getElementById("c");
function FC_CF() {
var temp; // Will hold the temperature value
var $targ; // Used to target the element we're not typing into:
if (this.id === "c") { // If we're typing into #c...
$targ = $f; // use #f as target element
temp = (this.value * 9 / 5) + 32; // C2F
} else {
$targ = $c;
temp = (this.value - 32) * 5 / 9; // F2C
}
// Write the result "as we type" in the other ($targ) field:
$targ.value = !isNaN(temp) ? parseFloat(temp.toFixed(1)) : "Err";
// (Above:) temp is a num ? return floated number, else: "Show some error"
}
// Assign input listeners to trigger the above function:
$f.oninput = FC_CF;
$c.oninput = FC_CF;
Celcius: <input id="c">
Fahrenheit: <input id="f">
You can separate the functions which do the temperature conversion as follows i did somw changes in the code.
<p>
<label>Fahrenheit</label>
<input id="outputFahrenheit" type="number" placeholder="Fahrenheit"
oninput="temperatureConverterCelsius(this.value)"
onchange="temperatureConverterCelsius(this.value)" value="">
</p>
<p>Celsius: </p>
<input id="outputCelsius" type="number" placeholder="Celsius"
oninput="temperatureConverterFahrenheit(this.value)"
onchange="temperatureConverterFahrenheit(this.value)" value="">
</p>
<script type=""text/javascript>
function temperatureConverterCelsius(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelsius").value = (valNum-32) / 1.8;
//document.getElementById("outputFahrenheit").value = (valNum*1.8)+32;
}
</script>
</body>
</html>
class Temperature_conversation {
constructor(celsius) {
this.celsius= celsius;
this.fahrenheit= 0;
this.table_begin= -50.0;
this.table_end= 50.0;
this.table_step= 10.0;
console.log('---------------------Conversion--------------------------');
console.log('Celsius fahrenheit');
for(this.celsius = this.table_begin; this.celsius <= this.table_end; this.celsius += this.table_step){
this.fahrenheit = this.celsiusToFahrenhit(celsius);
}
}
celsiusToFahrenhit(c){
const minimun_celsius = -273.15;
if (c < minimun_celsius) {
throw 'O argumento es pequeno';
}
this.celsius = (9.0 / 5.0) * c+ 32;
var res = [this.celsius, this.fahrenheit]
console.table(res);
}
}

Categories