JavaScript html forms calculator not working - javascript

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

Related

jquery - get a value in mix radio button

Would you like to check what wrong in my code, I have 2 group radio button when I click the radio button variable r not have a value :
<script>
$(document).ready(function() {
var s = 0;
var l = 0;
var r = 0;
$('input[type=radio][name="saverity"]').change(function() {
s = $(this).val();
console.log(s);
});
$('input[type=radio][name="likehood"]').change(function() {
l = $(this).val();
console.log(l);
});
r = s * l;
console.log(r);
});
Thank you very much.
Something like this should work.
$(document).ready(function() {
var s = 0;
var l = 0;
var r = 0;
$('input[type=radio][name="saverity"]').change(function() {
s = $(this).val();
recalculate();
});
$('input[type=radio][name="likehood"]').change(function() {
l = $(this).val();
recalculate();
});
function recalculate(){
r = s * l;
console.log(r);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
Saverity
<input type="radio" name="saverity" value="0">
<input type="radio" name="saverity" value="1">
</label>
<br>
<label>
Likehood
<input type="radio" name="likehood" value="0">
<input type="radio" name="likehood" value="1">
</label>

How to sum two results in Javascript

I am new at this and I got stuck.
I want to sum the two results that I get with this code.
$(document).ready(function() {
$('label').click(function() {
var total = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
$('#total').html(total + ' $');
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="myNumber">
<button onclick="myFunction()">Sum</button>
<p id="demo"></p>
<br>
<label><input type="checkbox" class="option" value="200" /> Name</label><br />
<label><input type="checkbox" class="option" value="300" /> Blah</label><br />
<label><input type="checkbox" class="option" value="400" /> XYZ</label><br />
<label><input type="checkbox" class="option" value="800" /> Something</label><br />
<label><input type="checkbox" class="option" value="1200" /> Item</label><br />
<br><br> Total :
<div id="total">0 $</div>
<br>
My question is - how to sum the two results and display it in 'Total:' at the end.
And how to remove the 'Sum' button, so you can see the result from the textbox in realtime in 'Total:' ?
Thanks in advance for any help :)
Edit : I need the sum from text box and the checkbox. For example : if the user have entered '5' this number equals 5 * 97 = 485. So '5' + Name(200) should be equals to 685.
Try this. I have defined a new method to calculate total amount. Whenever the checkbox or textbox is changed, the total is updated.
$(document).ready(function() {
document.getElementById("demo").innerHTML = 0;
$('label').click(function() {
$('.option:checked').each(function() {
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
updateTotal();
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
} else {
document.getElementById("demo").innerHTML = 0;
};
updateTotal();
}
function updateTotal(){
var total = 0;
var totalAmount = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
});
totalAmount = total + parseInt(document.getElementById("demo").innerHTML);
$('#total').html( totalAmount +' $');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="myNumber" onkeyup="myFunction()">
<p id="demo"></p>
<br>
<label><input type="checkbox" class="option" value="200" /> Name</label><br />
<label><input type="checkbox" class="option" value="300" /> Blah</label><br />
<label><input type="checkbox" class="option" value="400" /> XYZ</label><br />
<label><input type="checkbox" class="option" value="800" /> Something</label><br />
<label><input type="checkbox" class="option" value="1200" /> Item</label><br />
<br><br> Total :
<div id="total">0 $</div>
<br>
Create a new element with ID totalHolder and inside both functions call a third function (e.g. showTotal()) to sum those values:
$(document).ready(function() {
$('label').click(function() {
var total = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
$('#total').html(total + ' $');
showTotal();
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
};
showTotal();
}
function showTotal(){
var result1= parseInt($('#total').html());
var result2= parseInt($('#demo').html());
$("#totalHolder").html(result1+result2);
}
In order to remove onClick from button, you just need to set a listener:
$(docuemnt).ready(function(){
$("#myNumber").change(function(){
//Call your function inside the listener
myFunction()
})
})
Not sure if this satisfies your issue, but you need to do a couple things.
You should wrap input fields within a form.
Why are you mixing vanilla JS and jQuery? Stick with one or the other.
You should not be afraid to modularize your application with various functions.
Move the element queries out of the processing functions, instead pass their values in.
You can toggle the class in one loop, see below.
/* jQuery plugins */
(function($) {
/** Checks-off one or more checkboxes in a list of elements. */
$.fn.check = function(checked) {
return this.each(function(index, item) {
if (checked) {
$(item).prop('checked', 'checked');
} else {
$(item).removeProp('checked');
}
});
};
})(jQuery);
$(document).ready(function() {
$('#myNumber').val(5); // Set value to 5.
$('.option').slice(0, 1).check(true); // Check the first checkbox.
$('label').on('click', handleUpdate); // Attach a 'click' listener for label
handleUpdate(); // Call the function.
});
function handleUpdate() {
var sum = sumValues();
var num = $('#myNumber').val();
var mult = getMultiplier(num);
var total = num * mult + sum;
$('#total').html(total.toFixed(2) + ' $');
$('#demo').html(mult);
}
function sumValues() {
var total = 0;
$('.option').each(function() {
var isChecked = $(this).is(':checked');
if (isChecked) total += parseInt($(this).val());
$(this).parent().toggleClass('checked', isChecked);
});
return total;
}
function getMultiplier(value) {
if (value < 5) {
return value;
}
switch (value) {
case 5:
case 6:
case 7:
return 97;
case 8:
case 9:
case 10:
return 87;
default:
return 82;
}
}
label {
display: block;
}
.checked {
background : gold !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="check-form">
<input type="number" id="myNumber">
<button onclick="handleUpdate(); return false;">Sum</button>
<p id="demo"></p>
<label><input type="checkbox" class="option" value="200" /> Name</label>
<label><input type="checkbox" class="option" value="300" /> Blah</label>
<label><input type="checkbox" class="option" value="400" /> XYZ</label>
<label><input type="checkbox" class="option" value="800" /> Something</label>
<label><input type="checkbox" class="option" value="1200" /> Item</label>
</form>
<br>Total :
<div id="total">0 $</div>

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

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>

How to get an input value dynamically and perform arithmetic operations using javascript

I have created two input text fields by which the user have to give two values. Using javascript, I need to get those values perform addition, subtraction, multiplication and division based on the checkbox checked. How to do that?
Here is my code..
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JS Assignment</title>
<script>
function changeCheckBox() {
try {
var max = document.myform.check.length;
var count = 0;
for (var i = 0; i < max; i++) {
if (document.myform.check[i].checked == true) {
count++;
serNoChecked = i;
}
}
if (count == 1) {
for (var i = 0; i < max; i++) {
if (document.myform.check[i].checked == false) {
document.myform.check[i].disabled = true;
}
}
} else if (count == 0) {
for (var i = 0; i < max; i++) {
document.myform.check[i].disabled = false;
}
}
if (null == max) return false;
if (count == 0) {
return true;
} else if (count > 0) {
return false;
}
} catch (e) {
alert(e.message);
}
}
</script>
<script type="text/javascript">
function arith()
{
var number1 = document.getElementById('num1').value;
var number2 = document.getElementById('num2').value;
x=num1 + num2;
var demoP=document.getElementById("demo")
demoP.innerHTML="x=" + x;
}
</script>
</head>
<body background="photo.jpg" onload="arith()">
<h3>Simple JavaScript Arithmetic Operations</h3>
<form name="myform" method="get">
Value 1 <input type ="text" id="num1"> <br><br>
Value 2 <input type="text" id="num2"> <br><br>
<input type="checkbox" name="check" value="check1" id="check1" onclick="changeCheckBox()">Addition<br>
<input type="checkbox" name="check" value="check2" id="check2" onclick="changeCheckBox()">Subtraction<br>
<input type="checkbox" name="check" value="check3" id="check3" onclick="changeCheckBox()">Multiplication<br>
<input type="checkbox" name="check" value="check4" id="check4" onclick="changeCheckBox()">Division<br><br>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
</body>
</html>
Try sending the value of the HTML into the function, and then use those as an if statement check (or switch statement).
<form name="myform" method="get">
Value 1 <input type ="text" id="num1"> <br><br>
Value 2 <input type="text" id="num2"> <br><br>
<input type="checkbox" name="check" id="check1">Addition<br>
<input type="checkbox" name="check" id="check2">Subtraction<br>
<input type="checkbox" name="check" id="check3">Multiplication <br>
<input type="checkbox" name="check" id="check4">Division<br><br>
<input type="submit" value="Submit">
<p id="demo"></p>
Notice the value attributes now have unique value. And you're sending that into the function as a parameter.
Now just have a function that returns what you want
var newVal = "Unset";
var plus = document.getElementById("check1");
var minus = document.getElementById("check2");
var times = document.getElementById("check3");
var divide = document.getElementById("check4");
var demoP=document.getElementById("demo");
plus.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1+n2;
demoP.innerHTML="x=" + newVal;
}
minus.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1-n2;
demoP.innerHTML="x=" + newVal;
}
times.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1*n2;
demoP.innerHTML="x=" + newVal;
}
divide.onclick = function() {
var n1 = parseFloat(document.getElementById('num1').value);
var n2 = parseFloat(document.getElementById('num2').value);
newVal = n1/n2;
demoP.innerHTML="x=" + newVal;
}

I want to check answer and display it on HTML page with Javascript

I am pretty new on Javascript coding. I'm creating a web page for surveys or testing by myself.
Now here is my code;
<form id="q1form">
<input type="radio" name="question1" value="1" id="q1"> true
<input type="radio" name="question1" value="0" id="q2"> false
</form>
<button onclick="myFunction()"> try </button>
function myFunction(){
var form = document.getElementById('q1form'),
s1 = form['question1'],
n;
for (n = 0; n < s1.length; n++) {
if (s1[n].checked) {
var soru1= parseInt(s1[n].value);
}
}
if(soru1==1){
document.writeln("Your answer is correct!");
}
else{
document.wirteln("Your answer is not correct");
}
}
In this code I want to display "Your answer is correct!" or other answer near the 'try' button. I can display answer with window.alert but I want to do it near button, in same page. Is it possible? How can I do it?
You could use a div next to the button <span id="feedback"></span> and then insert the feedback into that div:
var feedback = document.getElementById("feedback");
feedback.innerHTML = "Your answer is correct!";
Something like
<form id="q1form">
<input type="radio" name="question1" value="1" id="q1">true
<input type="radio" name="question1" value="0" id="q2">false
</form>
<button onclick="myFunction(this)">try</button>
<script>
function myFunction(btn) {
var form = document.getElementById('q1form'),
s1 = form['question1'],
p = document.createElement('p'),
txt,
n;
for (n = 0; n < s1.length; n++) {
if (s1[n].checked) {
var soru1 = parseInt(s1[n].value);
}
}
if (soru1 == 1) {
txt = "Your answer is correct!"
} else {
txt = "Your answer is not correct";
}
var oldP = document.getElementById('response');
if (oldP) oldP.parentNode.removeChild(oldP);
p.appendChild(document.createTextNode(txt));
p.id = "response";
btn.parentNode.insertBefore(p, btn.nextSibling);
}
</script>
FIDDLE
This should get you started:
function myFunction() {
var form = document.getElementById('q1form'),
output = document.getElementById('output'),
s1 = form['question1'],
n;
for (n = 0; n < s1.length; n++) {
if (s1[n].checked) {
var soru1 = parseInt(s1[n].value);
}
}
output.innerHTML = soru1 === 1 ? "Your answer is correct!"
: "Your answer is not correct" ;
}
Working fiddle here.
You can use:
<form id="q1form">
<input type="radio" name="question1" value="1" id="q1"> true
<input type="radio" name="question1" value="0" id="q2"> false
</form>
<button onclick="myFunction()"> try </button>
<span id="demo"></span>
function myFunction(){
var form = document.getElementById('q1form'),
s1 = form['question1'],
n;
for (n = 0; n < s1.length; n++) {
if (s1[n].checked) {
var soru1= parseInt(s1[n].value);
}
}
if(soru1==1){
document.getElementById("demo").innerHTML="Your answer is correct";
}
else{
document.getElementById("demo").innerHTML="Your answer is not correct";
}
}

Categories

Resources