These are my codes. I don't know why I keep getting NaN? Please help me on this one. My textbox value comes from a dropdown that whatever the user chooses, a corresponding value will appear on the textbox that's why i used value="" I don't know if its the part that I got wrong. Please tell me how to deal with this NaN.
JS
function subtotal(){
var as = $("#as").val();
var txt1 = $('#sff').val();
var txt2 = $('#osf').val();
var d = 0;
var e = 0;
var f = 0;
var g = 0;
var a = parseFloat(as, 10);
var b = parseFloat(txt1, 10);
var c = parseFloat(txt2, 10);
if ($('#cbx3').is(":checked")) {
d = parseFloat($("#cbx3").val(), 10);
}
if ($('#cbx4').is(":checked")) {
e = parseFloat($("#cbx4").val(), 10);
}
if ($('#cbx5').is(":checked")) {
f = parseFloat($("#cbx5").val(), 10);
}
if ($('#cbx6').is(":checked")) {
g = parseFloat($("#cbx6").val(), 10);
}
var total = a + b + c + d + e + f + g;
$('#st').val(total.toFixed(2));
}
function grandtotal(){
var x = document.getElementById("st").value;
var y = document.getElementById("shppng").value;
var sum = parseFloat(x, 10)+ parseFloat(y, 10);
$("#gt").val(sum.toFixed(2));
HTML
<input type="text" id="sff" placeholder="$0.00" value="" style="float:left;"/>
<input type="text" id="osf" placeholder="$0.00" value="" style="float:left;"/>
<select id="as" style="margin: 3px 0 0 55px; width:48%; position: absolute; float: left;">
<option value="99.00">$99.00/</option>
<option value="178.20">$178.20</option>
<option value="241.56">$241.56</option>
<option value="292.24">$292.24</option>
<option value="332.80">$332.80</option>
</select>
<input type="checkbox" id="cbx4" value="69.00"/>
<input type="checkbox" id="cbx5" value="35.00"/>
input type="checkbox" id="cbx6" value="39.00"/>
Specify default value.
<input type="text" id="sff" placeholder="$0.00" value="0" style="float:left;"/>
<input type="text" id="osf" placeholder="$0.00" value="0" style="float:left;"/>
The value of a, b or c can be blank so
function subtotal() {
var as = $("#as").val();
var txt1 = $('#sff').val();
var txt2 = $('#osf').val();
var d = 0;
var e = 0;
var f = 0;
var g = 0;
var a = parseFloat(as, 10) || 0;
var b = parseFloat(txt1, 10) || 0;
var c = parseFloat(txt2, 10) || 0;
if ($('#cbx3').is(":checked")) {
d = parseFloat($("#cbx3").val(), 10);
}
if ($('#cbx4').is(":checked")) {
e = parseFloat($("#cbx4").val(), 10);
}
if ($('#cbx5').is(":checked")) {
f = parseFloat($("#cbx5").val(), 10);
}
if ($('#cbx6').is(":checked")) {
g = parseFloat($("#cbx6").val(), 10);
}
var total = a + b + c + d + e + f + g;
$('#st').val(total.toFixed(2));
}
function grandtotal() {
var x = document.getElementById("st").value;
var y = document.getElementById("shppng").value;
var sum = parseFloat(x, 10) + parseFloat(y, 10);
$("#gt").val(sum.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="sff" placeholder="$0.00" value="" style="float:left;" />
<input type="text" id="osf" placeholder="$0.00" value="" style="float:left;" />
<select id="as">
<option value="99.00">$99.00/</option>
<option value="178.20">$178.20</option>
<option value="241.56">$241.56</option>
<option value="292.24">$292.24</option>
<option value="332.80">$332.80</option>
</select>
<input type="checkbox" id="cbx4" value="69.00" />
<input type="checkbox" id="cbx5" value="35.00" />
<input type="checkbox" id="cbx6" value="39.00" />
<br />
<input id="st" />
<input id="gt" />
<br />
<input type="button" value="Total" onclick="subtotal(); grandtotal();" />
Related
How to edit the code so that the function calculateTotal can run when the submit button is pressed, and the output is how after the submit button press but not directly show to people by keep adding.
var person = [];
person["person1"]=1;
person["person2"]=2;
person["person3"]=3;
person["person4"]=4;
person["person5"]=5;
var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100*(5455/12);
elec["elec2"] = 150*(5455/12);
elec["elec3"] = 200*(5455/12);
elec["elec4"] = 250*(5455/12);
elec["elec5"] = 300*(5455/12);
elec["elec6"] = 350*(5455/12);
elec["elec7"] = 400*(5455/12);
elec["elec8"] = 450*(5455/12);
elec["elec9"] = 500*(5455/12);
elec["elec10"] = 550*(5455/12);
elec["elec11"] = 600*(5455/12);
elec["elec12"] = 650*(5455/12);
elec["elec13"] = 700*(5455/12);
function getNumberperson()
{
var numberperson=0;
var theForm = document.forms["energyform"];
var selectedPerson = theForm.elements["selectedperson"];
for(var i = 0; i < selectedPerson.length; i++)
{
if(selectedPerson[i].checked)
{
numberperson = person[selectedPerson[i].value];
}
}
return numberperson;
}
function getElectotal()
{
var electotal=0;
var theForm = document.forms["energyform"];
var selectedElec = theForm.elements["electricity"];
electotal = elec[selectedElec.value];
return electotal;
}
function waste()
{
var mustwaste=0;
var theForm = document.forms["energyform"];
var waste = theForm.elements["waste"];
if(waste.checked==true)
{
mustwaste=(692/12);
}
return mustwaste;
}
function recyclealu()
{
var recyclealu=0;
var theForm = document.forms["energyform"];
var yesalu = theForm.elements["yesalu"];
if(yesalu.checked==true)
{
recyclealu=-89.38;
}
return recyclealu;
}
function recycleplas()
{
var recycleplas=0;
var theForm = document.forms["energyform"];
var yesplas = theForm.elements["yesplas"];
if(yesplas.checked==true)
{
recycleplas=-35.56;
}
return recycleplas;
}
function checkAllRecycles() {
const recycleBoxes = document.querySelectorAll('.recycle');
if (recycleBoxes) {
recycleBoxes.forEach((recycleBox) => {
if (!recycleBox.checked) {
recycleBox.checked = 'checked';
}
})
}
calculateTotal();
}
function calculateTotal()
{
var totalco = getNumberperson()*getElectotal() + waste() + recyclealu() + recycleplas();
//display the result
document.getElementById('totalConsumption').innerHTML = +totalco.toFixed(2);
}
//add a function to hide the result on page loading at the start
function hideTotal()
{
document.getElementById('totalConsumption').innerHTML = "0";
}
function vwaste()
{
var cw = document.getElementsByName('waste');
for (var i = 0; i < cw.length; i++)
{
if (cw[i].type == 'checkbox')
{
if (cw[i].checked) {return true}
}
}
return false;
}
function allvalidate()
{
var error = document.getElementById("error")
if (!vwaste())
{
// Changing content and color of content
error.textContent = "Waste must be select"
error.style.color = "red"
return false;
}
return true;
}
<body onload='hideTotal()'>
<div id="all">
<form action="/action_page.php" id="energyform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Carbon Footprint Calculator</legend>
<label >Number of Person Live in Household</label><br/>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person1" onclick="calculateTotal()" />1 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person2" onclick="calculateTotal()" />2 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person3" onclick="calculateTotal()" />3 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person4" onclick="calculateTotal()" />4 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person5" onclick="calculateTotal()" />5 </label>
<br/>
<label><i class="fa fa-flash"></i>Waste</label>
<input type="checkbox" id="waste" name='waste' onclick="calculateTotal()" /><span id="error"></span>
<hr><label><i class="fa fa-flash"></i>Energy Consumption Per Month</label></hr>
<br/>
<label> Electricity    </label>
<select id="electricity" name='electricity' onchange="calculateTotal()">
<option value="elecuse">0kWh</option>
<option value="elec1">100kWh</option>
<option value="elec2">150kWh</option>
<option value="elec3">200kWh</option>
<option value="elec4">250kWh</option>
<option value="elec5">300kWh</option>
<option value="elec6">350kWh (Avg US)</option>
<option value="elec7">400kWh (Avg MY)</option>
<option value="elec8">450kWh</option>
<option value="elec9">500kWh (Avg AS)</option>
<option value="elec10">550kWh</option>
<option value="elec11">600kWh</option>
<option value="elec12">650kWh</option>
<option value="elec13">700kWh</option>
</select>
<hr><label><i class="fa fa-flash"></i>Recycle </label></hr>
<br/>
<label for='yesalu' class="alu"> Aluminium and Steel  </label>
<input type="checkbox" id="yesalu" name='yesalu' class="recycle" onclick="calculateTotal()" />
<br/>
<label for='yesplas' class="plas"> Plastic                          </label>
<input type="checkbox" id="yesplas" name='yesplas' class="recycle" onclick="calculateTotal()" />
<br/>
<button type="button" onclick="checkAllRecycles()">Select All</button>
<br/>
<p>Total CO2 produced per year per household:</p>
<div id="totalConsumption">0</div>
<label>pounds</label>
<div>US Household average is 21,820 lbs per year.</div>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
<input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
</div>
</form>
</div>
</body>
Move the call to calculateTotal() to the form's onsubmit instead of doing it in all the onclick.
Also take calls to it out of other functions.
var person = [];
person["person1"] = 1;
person["person2"] = 2;
person["person3"] = 3;
person["person4"] = 4;
person["person5"] = 5;
var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100 * (5455 / 12);
elec["elec2"] = 150 * (5455 / 12);
elec["elec3"] = 200 * (5455 / 12);
elec["elec4"] = 250 * (5455 / 12);
elec["elec5"] = 300 * (5455 / 12);
elec["elec6"] = 350 * (5455 / 12);
elec["elec7"] = 400 * (5455 / 12);
elec["elec8"] = 450 * (5455 / 12);
elec["elec9"] = 500 * (5455 / 12);
elec["elec10"] = 550 * (5455 / 12);
elec["elec11"] = 600 * (5455 / 12);
elec["elec12"] = 650 * (5455 / 12);
elec["elec13"] = 700 * (5455 / 12);
function getNumberperson() {
var numberperson = 0;
var theForm = document.forms["energyform"];
var selectedPerson = theForm.elements["selectedperson"];
for (var i = 0; i < selectedPerson.length; i++) {
if (selectedPerson[i].checked) {
numberperson = person[selectedPerson[i].value];
}
}
return numberperson;
}
function getElectotal() {
var electotal = 0;
var theForm = document.forms["energyform"];
var selectedElec = theForm.elements["electricity"];
electotal = elec[selectedElec.value];
return electotal;
}
function waste() {
var mustwaste = 0;
var theForm = document.forms["energyform"];
var waste = theForm.elements["waste"];
if (waste.checked == true) {
mustwaste = (692 / 12);
}
return mustwaste;
}
function recyclealu() {
var recyclealu = 0;
var theForm = document.forms["energyform"];
var yesalu = theForm.elements["yesalu"];
if (yesalu.checked == true) {
recyclealu = -89.38;
}
return recyclealu;
}
function recycleplas() {
var recycleplas = 0;
var theForm = document.forms["energyform"];
var yesplas = theForm.elements["yesplas"];
if (yesplas.checked == true) {
recycleplas = -35.56;
}
return recycleplas;
}
function checkAllRecycles() {
const recycleBoxes = document.querySelectorAll('.recycle');
if (recycleBoxes) {
recycleBoxes.forEach((recycleBox) => {
if (!recycleBox.checked) {
recycleBox.checked = 'checked';
}
})
}
}
function calculateTotal() {
var totalco = getNumberperson() * getElectotal() + waste() + recyclealu() + recycleplas();
//display the result
document.getElementById('totalConsumption').innerHTML = +totalco.toFixed(2);
}
//add a function to hide the result on page loading at the start
function hideTotal() {
document.getElementById('totalConsumption').innerHTML = "0";
}
function vwaste() {
var cw = document.getElementsByName('waste');
for (var i = 0; i < cw.length; i++) {
if (cw[i].type == 'checkbox') {
if (cw[i].checked) {
return true
}
}
}
return false;
}
function allvalidate() {
var error = document.getElementById("error")
if (!vwaste()) {
// Changing content and color of content
error.textContent = "Waste must be select"
error.style.color = "red"
return false;
}
return true;
}
<body onload='hideTotal()'>
<div id="all">
<form action="/action_page.php" id="energyform" onsubmit="calculateTotal();return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Carbon Footprint Calculator</legend>
<label>Number of Person Live in Household</label><br/>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person1"/>1 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person2" />2 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person3" />3 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person4" />4 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person5" />5 </label>
<br/>
<label><i class="fa fa-flash"></i>Waste</label>
<input type="checkbox" id="waste" name='waste' /><span id="error"></span>
<hr><label><i class="fa fa-flash"></i>Energy Consumption Per Month</label></hr>
<br/>
<label> Electricity    </label>
<select id="electricity" name='electricity' >
<option value="elecuse">0kWh</option>
<option value="elec1">100kWh</option>
<option value="elec2">150kWh</option>
<option value="elec3">200kWh</option>
<option value="elec4">250kWh</option>
<option value="elec5">300kWh</option>
<option value="elec6">350kWh (Avg US)</option>
<option value="elec7">400kWh (Avg MY)</option>
<option value="elec8">450kWh</option>
<option value="elec9">500kWh (Avg AS)</option>
<option value="elec10">550kWh</option>
<option value="elec11">600kWh</option>
<option value="elec12">650kWh</option>
<option value="elec13">700kWh</option>
</select>
<hr><label><i class="fa fa-flash"></i>Recycle </label></hr>
<br/>
<label for='yesalu' class="alu"> Aluminium and Steel  </label>
<input type="checkbox" id="yesalu" name='yesalu' class="recycle" />
<br/>
<label for='yesplas' class="plas"> Plastic                          </label>
<input type="checkbox" id="yesplas" name='yesplas' class="recycle" />
<br/>
<button type="button" onclick="checkAllRecycles()">Select All</button>
<br/>
<p>Total CO2 produced per year per household:</p>
<div id="totalConsumption">0</div>
<label>pounds</label>
<div>US Household average is 21,820 lbs per year.</div>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
<input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
</div>
</form>
</div>
</body>
i want to add the first and second function value in third function.and i am using this third function value to display on one textbox.
i have tried to directly add the function and get the result but it doesnt work
i tried different function like onkeydown, onkeypress etc.
//first function
function first() {
var tt = parseInt(document.getElementById("divi").value);
var pp = parseInt(document.getElementById("npt").value)
var tl = parseInt(document.getElementById("tlpw").value)
document.getElementById("ttlpw").value = tt * pp * tl;
}
//second function
function second() {
var tt = parseInt(document.getElementById("npp").value);
var pp = parseInt(document.getElementById("plpw").value)
var tl = parseInt(document.getElementById("nob").value)
document.getElementById("tplpw").value = tt * pp * tl;
}
//third function
function third() {
X = first();
Y = second();
document.getElementById("twork").value = x + y;
}
<input type="text" id="cname" name="cname" class="form-control" />
<input type="text" id="npt" name="npt" onkeyup="first()" class="form-control" />
<input type="text" id="npp" name="npp" onkeyup="second()" class="form-control" />
<input type="text" id="tlpw" name="tlpw" onkeyup="first()" class="form-control" />
<input type="text" id="plpw" name="plpw" onkeyup="second()" class="form-control" />
<input type="text" id="divi" name="divi" onkeyup="first()" class="form-control" />
<input type="text" id="nseb" name="nseb" class="form-control" />
<input type="text" id="nob" name="nob" onkeyup="second()" class="form-control" />
<input type="text" id="ttlpw" name="ttlpw" " onkeyup="third() "
class="form-control " />
<input type="text " id="tplpw " name="tplpw "" onkeyup="third()" class="form-control" />
<input type="text" id="twork" name="twork" class="form-control" />
This code does not give the addition of the value. I am expecting addition of x+y.
There are several issues:
Your functions first() and second() print the value, but they don't actually return those values.
On top of that, you have superfluous/random " characters and space characters which cause your inputs to not behave as expected.
Finally, you assign X and Y and then try to add x and y, but Javascript is case sensitive so the addition tries to add two undefined values.
In the below snippet (click Show to see it) I fixed all of that, and I added placeholders so at least we have some indication of what we are typing into.
As a last note, it looks like cname and nseb are not being used anywhere, also they do not have a keyup event like most of the others.
It still looks a bit messy to me; I hope it makes more sense to you.
// Give all inputs a placeholder
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].placeholder = inputs[i].id;
}
function first() {
var tt = parseInt(document.getElementById("divi").value);
var pp = parseInt(document.getElementById("npt").value);
var tl = parseInt(document.getElementById("tlpw").value);
var value = tt * pp * tl;
document.getElementById("ttlpw").value = value;
return value;
}
function second() {
var tt = parseInt(document.getElementById("npp").value);
var pp = parseInt(document.getElementById("plpw").value)
var tl = parseInt(document.getElementById("nob").value)
var value = tt * pp * tl;
document.getElementById("tplpw").value = value;
return value;
}
function third() {
var x = first();
var y = second();
document.getElementById("twork").value = x + y;
}
<input type="text" id="cname" name="cname" class="form-control" />
<input type="text" id="npt" name="npt" onkeyup="first()" class="form-control" />
<input type="text" id="npp" name="npp" onkeyup="second()" class="form-control" />
<input type="text" id="tlpw" name="tlpw" onkeyup="first()" class="form-control" />
<input type="text" id="plpw" name="plpw" onkeyup="second()" class="form-control" />
<input type="text" id="divi" name="divi" onkeyup="first()" class="form-control" />
<input type="text" id="nseb" name="nseb" class="form-control" />
<input type="text" id="nob" name="nob" onkeyup="second()" class="form-control" />
<input type="text" id="ttlpw" name="ttlpw" onkeyup="third()" class="form-control " />
<input type="text" id="tplpw" name="tplpw" onkeyup="third()" class="form-control" />
<input type="text" id="twork" name="twork" class="form-control" />
Update:
If I understand your need correctly, instead of doing onkeyup="first()" and onkeyup="second()", try changing them all to use onkeyup="third()". third() will call both the other functions, each of which will show their outcome, and then third() will show the sum of both.
Here is a new snippet that will do that. I also removed cname and nseb, and rearranged the order of inputs so they actually make sense.
// Give all inputs a placeholder
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].placeholder = inputs[i].id;
}
function first() {
var tt = parseInt(document.getElementById("divi").value);
var pp = parseInt(document.getElementById("npt").value);
var tl = parseInt(document.getElementById("tlpw").value);
var value = tt * pp * tl;
document.getElementById("ttlpw").value = value;
return value;
}
function second() {
var tt = parseInt(document.getElementById("npp").value);
var pp = parseInt(document.getElementById("plpw").value)
var tl = parseInt(document.getElementById("nob").value)
var value = tt * pp * tl;
document.getElementById("tplpw").value = value;
return value;
}
function third() {
var x = first();
var y = second();
document.getElementById("twork").value = x + y;
}
div { width: 240px; text-align: right; }
input { width: 40px; }
<div>
<input type="text" id="npt" name="npt" onkeyup="third()" /> *
<input type="text" id="divi" name="divi" onkeyup="third()" /> *
<input type="text" id="tlpw" name="tlpw" onkeyup="third()" /> =
<input type="text" id="ttlpw" name="ttlpw" onkeyup="third()" /><br />
<input type="text" id="npp" name="npp" onkeyup="third()" /> *
<input type="text" id="nob" name="nob" onkeyup="third()" /> *
<input type="text" id="plpw" name="plpw" onkeyup="third()" /> =
<input type="text" id="tplpw" name="tplpw" onkeyup="third()" /><br />
<input type="text" id="twork" name="twork" /><br />
</div>
You need that functions first and second to return the value:
function first () {
...
return tt * pp * tl
}
The code wont show the total in the textbox I need your help with my code please.
code here:
<script>
function optTotal()
{
var a = document.frm.optA.value;
if (!a)
a = '0';
var b = document.frm.optB.value;
if (!b)
b = '0';
var c = document.frm.optC.value;
if (!c)
c = '0';
var d = document.frm.optD.value;
if (!d)
d = '0';
var optA = parseFloat(a);
var optB = parseFloat(b);
var optC = parseFloat(c);
var optD = parseFloat(d);
document.frm.total.value = optA + optB + optC + optD;
}
</script>
code here:
<form method="post" action="index.php" name="frm" id="frm" >
<input type="text" name="name" />
<input type="radio" name="optA" value="1" onclick="optTotal()" />1
<input type="radio" name="optA" value="2" onclick="optTotal()" />2
<input type="radio" name="optA" value="3" onclick="optTotal()" />3
<input type="radio" name="optB" value="1" onclick="optTotal()" />1
<input type="radio" name="optB" value="2" onclick="optTotal()" />2
<input type="radio" name="optB" value="3" onclick="optTotal()" />3
<input type="radio" name="optC" value="1" onclick="optTotal()" />1
<input type="radio" name="optC" value="2" onclick="optTotal()" />2
<input type="radio" name="optC" value="3" onclick="optTotal()" />3
<input type="radio" name="optD" value="1" onclick="optTotal()" />1
<input type="radio" name="optD" value="2" onclick="optTotal()" />2
<input type="radio" name="optD" value="3" onclick="optTotal()" />3
<input type="text" name="total" id="total" onkeyup="optTotal()" />
<input type="submit" value="enter" name="calculate" />
</form>
I want my code to show real time output in the textbox.
Follow the below step
var a1 = document.querySelector('input[name="optA"]:checked');
var b1 = document.querySelector('input[name="optB"]:checked');
var c1 = document.querySelector('input[name="optC"]:checked');
var d1 = document.querySelector('input[name="optD"]:checked');
if (a1 != null)
a1 = parseFloat(a1.value);
else
a1 = 0;
if (b1 != null)
b1 = parseFloat(b1.value);
else
b1 = 0;
if (c1 != null)
c1 = parseFloat(c1.value);
else
c1 = 0;
if (d1 != null)
d1 = parseFloat(d1.value);
else
d1 = 0;
document.frm.total.value=parseFloat(a1)+parseFloat(b1)+parseFloat(c1)+parseFloat(d1);
DEMO Click any option of first row, i have modified that for demo
document.frm.optA returns the array of nodelist, means all the radio buttons whose names are optA
You have to
var a = document.frm.optA // This will return all radio buttons whoose names are optA
for(var i=0;i<a.length;i++)
{
if(a[i].checked)
{
alert(a[i].value);
}
}
I have created a script to solve your problem, Please have a look.
function getCheckedRadio(radio_group) {
var radio_group = document.getElementsByName(radio_group);
for (var i = 0; i < radio_group.length; i++) {
var button = radio_group[i];
if (button.checked) {
return button.value;
}
}
return undefined;
}
function optTotal()
{
var a = getCheckedRadio("optA");// pass radio button group name
if (!a)
a = '0';
var b = getCheckedRadio("optB");// pass radio button group name
if (!b)
b = '0';
var c = getCheckedRadio("optC");// pass radio button group name
if (!c)
c = '0';
var d = getCheckedRadio("optD");// pass radio button group name
if (!d)
d = '0';
var optA = parseFloat(a);
var optB = parseFloat(b);
var optC = parseFloat(c);
var optD = parseFloat(d);
document.frm.total.value = optA + optB + optC + optD;
}
I'm very new to Javascript and Jquery and am attempting to use this script externally to calculate the value of a users selections (Radio buttons and Checkboxes) and then output the value of the function into my HTML page (id cost) by pressing a button (id submit). This is what I have so far, I would be very appreciative if someone could help me understand why it isn't working.
function add() {
var val1 = 0;
for (i = 0; i < document.form1."radio-choice-v-1"; i++)
{
if (document.form1."radio-choice-v-1"[i].checked === true)
{
val1 = document.form1."radio-choice-v-1"[i].value;
}
}
var val2 = 0;
for (i = 0; i < document.form2."radio-choice-v-2"; i++)
{
if (document.form2.radio-"choice-v-2"[i].checked === true)
{
val2 = document.form2."radio-choice-v-2"[i].value;
}
}
var val3 = 0;
for (i = 0; i < document.form3."radio-choice-v-3"; i++)
{
if (document.form3."radio-choice-v-3"[i].checked === true)
{
val3 = document."form3.radio-choice-v-3"[i].value;
}
}
var val4 = 0;
for (i = 0; i < document.form4."radio-choice-v-4"; i++)
{
if (document.form4."radio-choice-v-4"[i].checked === true)
{
val4 = document.form4."radio-choice-v-4"[i].value;
}
}
var val5 = 0;
for (i = 0; i < document.form5."radio-choice-v-5"; i++)
{
if (document.form5."radio-choice-v-5"[i].checked === true)
{
val5 = document.form5."radio-choice-v-5"[i].value;
}
}
var val6 = 0;
for( i = 0; i < document.form6."checkselection"; i++ )
{
val6 = document.form6."checkselection"[i].value;
}
$("cost").html(" = " + (val1 + val2 + val3 + val4 + val5 + val6));
}
<form name="form1" id="form1">
<fieldset data-role="controlgroup">
<legend>Please select a case:</legend>
<input id="radio-choice-v-1a" name="radio-choice-v-1" value="40" CHECKED="checked" type="radio">
<label for="radio-choice-v-1a">Choice 1 (£40)</label>
<input id="radio-choice-v-1b" name="radio-choice-v-1" value="45" type="radio">
<label for="radio-choice-v-1b">Choice 2 (£45)</label>
<input id="radio-choice-v-1c" name="radio-choice-v-1" value="140" type="radio">
<label for="radio-choice-v-1c">Choice 3 (£140)</label>
</fieldset>
</form>
<form name="form6" id="form6">
<fieldset data-role="controlgroup">
<legend>Select your extras</legend>
<input type="Checkbox" name="checkselection" id="checkbox-extra-1" value="20">
<label for="checkbox-extra-1"> Selection 1 (£20) (recommended)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-2" value="12">
<label for="checkbox-extra-2">Selection 2 (£12)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-3" value="4">
<label for="checkbox-extra-3">Selection 3 (£4)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-4" value="30">
<label for="checkbox-extra-4">Selection 4 (£30)</label>
</fieldset>
</form>
<form>
<input id="submit" type="button" value="Submit" onclick="add();">
</form>
£<u id="cost"></u>
There where quite a few problems with your code. Please have a look at the working example I created on JSFiddle for you:
http://jsfiddle.net/95SrV/1/
I had to comment out the val2+ because you did not have those other forms in the sample HTML you provided:
Pure JavaScript
var val1 = 0;
for (i = 0; i < document.form1["radio-choice-v-1"].length; i++) {
if (document.form1["radio-choice-v-1"][i].checked === true) {
val1 = document.form1["radio-choice-v-1"][i].value;
}
}
However, if you do want to full use jQuery you could use the following code instead:
Full jQuery
var val1 = 0;
$('[name="radio-choice-v-1"]').each(function() {
currentItem = $(this);
if (currentItem.is(":checked")) {
val1 = currentItem.val();
}
});
Try with this one. Make sure all elements will be available like "radio-choice-v-2".
function add() {
var val1 = 0;
for (var i = 0; i < document.form1["radio-choice-v-1"].length; i++)
{
if (document.form1["radio-choice-v-1"][i].checked === true)
{
val1 = document.form1["radio-choice-v-1"][i].value;
}
}
var val2 = 0;
for (i = 0; i < document.form2["radio-choice-v-2"].length; i++)
{
if (document.form2["radio-choice-v-2"][i].checked === true)
{
val2 = document.form2["radio-choice-v-2"][i].value;
}
}
var val3 = 0;
for (i = 0; i < document.form3["radio-choice-v-3"].length; i++)
{
if (document.form3["radio-choice-v-3"][i].checked === true)
{
val3 = document.form3["form3.radio-choice-v-3"][i].value;
}
}
var val4 = 0;
for (i = 0; i < document.form4["radio-choice-v-4"].length; i++)
{
if (document.form4["radio-choice-v-4"][i].checked === true)
{
val4 = document.form4["radio-choice-v-4"][i].value;
}
}
var val5 = 0;
for (i = 0; i < document.form5["radio-choice-v-5"].length; i++)
{
if (document.form5["radio-choice-v-5"][i].checked === true)
{
val5 = document.form5["radio-choice-v-5"][i].value;
}
}
var val6 = 0;
for( i = 0; i < document.form6["checkselection"].length; i++ )
{
if (document.form6["checkselection"][i].checked === true) //Are you missing check here
val6 += document.form6["checkselection"][i].value; // += added here
}
$("#cost").html(" = " + (val1 + val2 + val3 + val4 + val5 + val6));
}
</script>
<form name="form1" id="form1">
<fieldset data-role="controlgroup">
<legend>Please select a case:</legend>
<input id="radio-choice-v-1a" name="radio-choice-v-1" value="40" CHECKED="checked" type="radio">
<label for="radio-choice-v-1a">Choice 1 (£40)</label>
<input id="radio-choice-v-1b" name="radio-choice-v-1" value="45" type="radio">
<label for="radio-choice-v-1b">Choice 2 (£45)</label>
<input id="radio-choice-v-1c" name="radio-choice-v-1" value="140" type="radio">
<label for="radio-choice-v-1c">Choice 3 (£140)</label>
</fieldset>
</form>
<form name="form6" id="form6">
<fieldset data-role="controlgroup">
<legend>Select your extras</legend>
<input type="Checkbox" name="checkselection" id="checkbox-extra-1" value="20">
<label for="checkbox-extra-1"> Selection 1 (£20) (recommended)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-2" value="12">
<label for="checkbox-extra-2">Selection 2 (£12)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-3" value="4">
<label for="checkbox-extra-3">Selection 3 (£4)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-4" value="30">
<label for="checkbox-extra-4">Selection 4 (£30)</label>
</fieldset>
</form>
<form>
<input id="submit" type="button" value="Submit" onclick="add();">
</form>
£<u id="cost"></u>
I have the form below
<form name="form1" id="form1" action="">
<table id="dateTable">
<tr>
<td>
<input type="text" name="date[]" value="" style="width: 25px;">
<input type="hidden" name="date[]" value="" style="width: 25px;">
<input type="text" name="month[]" value="" style="width: 25px;">
<input type="hidden" name="month[]" value="" style="width: 25px;">
<input type="text" name="year[]" value="" style="width: 40px;">
<input type="hidden" name="year[]" value="" style="width: 40px;">
<button onClick="cal_date_1.showCalendar('cal_date_1'); return false;">
<img src="php/kantoor/templates/default/images/agenda.gif">
</button>
<div id="cal_date_1" class="cal_date"></div>
</td>
<td class="td_formfield_text"><img src="php/kantoor/templates/default/images/plus.gif" onclick="addRow();" title="Add" alt="Toevoegen prijs buiten pakket"></td>
</tr>
</table>
</form>
When I click on button it show the calendar. Choose one date it will set to date, month, year input with the javascript below
var date = document.form1.elements["date[]"];
var month = document.form1.elements["month[]"];
var year = document.form1.elements["year[]"];
var cal_date_1 = new CalendarPopup( "cal_date_1", 0, 0);
cal_date_1.setReturnFunction( "cal_date_change_1" );
cal_date_1.setWeekStartDay(1);
function cal_date_change_1( y, m, d ) {
date[0].value = LZ(d);
month[0].value = LZ(m);
year[0].value = LZ(y);
}
When I click on the plus image to add more row it will run the function
function addRow() {
var dateTable = document.getElementById("dateTable");
var noRow = dateTable.rows.length;
dateTable.insertRow(-1);
tr = dateTable.rows[noRow];
tr.insertCell(-1);
td = tr.cells[0];
dateInput = document.createElement("input");
dateInput.type = "text";
dateInput.name = "date[]";
dateInput.style.width = 25;
monthInput = document.createElement("input");
monthInput.type = "text";
monthInput.name = "month[]";
monthInput.style.width = 25;
yearInput = document.createElement("input");
yearInput.type = "text";
yearInput.name = "year[]";
yearInput.style.width = 40;
td.appendChild(dateInput);
td.appendChild(monthInput);
td.appendChild(yearInput);
dateButton = document.createElement("button");
dateButton.setAttribute("id", "datum_bewerken_button_1");
var img = document.createElement("img");
img.src = "php/kantoor/templates/default/images/agenda.gif";
img.style.width = 16;
img.style.height = 15;
img.style.border = 0;
dateButton.appendChild(img);
td.appendChild(dateButton);
var div = document.createElement("div");
div.setAttribute("id", "cal_date_" + noRow);
for (var i = 2; i <= noRow; i++) {
dateButton.onclick = function () {
window['cal_date_'+i].showCalendar('cal_date_' + noRow);
return false;
}
window['cal_date_'+i] = new CalendarPopup( "cal_date_" + i, 0, 0);
window['cal_date_'+i].setReturnFunction("cal_date_change_" + i);
window['cal_date_'+i].setWeekStartDay( 1 );
}
}
I don't know how to set window['cal_date_'+i].showCalendar('cal_date_' + noRow); this code don't work and how to create callback function for window['cal_date_'+i].setReturnFunction("cal_date_change_" + i);
Please help me. Thanks in advance.