Checkbox Calculations Not Working - javascript

Hey guys i have a question about calculating checkboxes and its total in real time so here is my code:
function calc()
{
theTotal = 0;
checkForm = document.FormName;
for (i=0; i <= checkForm.length-1; i++) {
if (checkForm.elements[i].type == "checkbox") {
if (checkForm.elements[i].checked == true) {
document.getElementById("total").value = theTotal;
}
}
}
document.getElementById("total").innerHTML = theTotal;
}
Here is my html code:
<p>Total: $<span id="total">0</span></p>
<tr>
<td> <br> <center> <img src="Shirt1.jpg" width="160" height="150" alt="shirt1"> <br> <input type="checkbox" onchange="calc()" value="19.99"> <label for="rd1">Obey T-Shirt: $19.99</label> </center> </br></td>
<td> <br> <center> <img src="Shoe1.jpg" width="160" height="150" alt="shoe1"> <br> <input type="checkbox" onchange="calc()" value="19.99"> <label for="rd1">Shoe - Red Lace: $19.99</label> </center> </br> </td>
<td> <br> <center> <img src="Snapback1.jpg" width="160" height="150" alt="snap1"> <br> <input type="checkbox" onchange="calc()" value="19.99"> <label for="rd1">Snapback Bullets: $19.99</label> </center> </br> </td>
</tr>
When i click on one of the selected checkboxes it won't give me the calculation that i want. Are you able to help me with this one?

There are lot of problems seems in your code. Here I am writing simpler for you.
You don't need to iterate over every form element, even when you are calling it separately with each checkbox.
You also need to make theTotal as global variable for having total of checked items. Right now you are resetting it to 0 on every function call.
You can try this
var theTotal = parseFloat(0);
function calc(control) {
if (control.checked == true) {
theTotal += parseFloat(control.value);
} else {
theTotal -= parseFloat(control.value);
}
document.getElementById("total").innerHTML = theTotal;
}
and call it like this
<input type="checkbox" onchange="calc(this)" value="19.99">
JS Fiddle Demo

you are not updating the variable total.
You should be reading the .value of the checked inputs

Related

How to check multiple checkboxes in Javascript

I've just started to learn JavaScript and have run into a issue trying to get multiple checkboxes to work.
I am trying to calculate the cost of a product based on the options checked. However, my script is automatically assuming that all the boxes have been checked.
What is wrong with this code? Sorry if its a basic question but I have been banging my head for hours now.
function cal() {
var selectionOne = 0;
var selectionTwo = 0;
var selectionThree = 0;
var total = 0;
if (document.getElementById("1").checked = true ){
selectionOne = 25;
}
if (document.getElementById("2").checked = true ){
selectionTwo = 50;
}
if (document.getElementById("3").checked = true ){
selectionThree = 100;
}
total = selectionOne + selectionTwo + selectionThree;
alert ("Your total is £" + total);
}
HTML
<html>
<head>
<title>Basic Pricing Script</title>
</head>
<body>
<script src="script.js"></script>
<p>Please select which options you want from the list</p>
<form name="priceoptions">
<input type="checkbox" id="1" name="big" value="big"> Big Prints<br>
<input type="checkbox" id="2" name="medium" value="medium" > Medium Prints<br>
<input type="checkbox" id="3" name="small" value="small" > Small Prints<br>
<input type="submit" id="button" value="Submit" onclick="cal()">
</form>
</body>
</html>
= is the assignment operator. For comparisons, you need to use == or ===.
==: This compares by type
=== This compares by type and value
Also, saying .checked == true is redundant. You can just use .checked. Furthermore, there is no reason to declare the variables, and then set their values on seperate lines. You can reduce the code by using the ternary operator.
Check out this snippet.
function cal() {
var s1 = document.getElementById("1").checked ? 25 : 0;
var s2 = document.getElementById("2").checked ? 50 : 0;
var s3 = document.getElementById("3").checked ? 100 : 0;
var total = s1 + s2 + s3;
alert ("Your total is £" + total);
}
<p>Please select which options you want from the list</p>
<form name="priceoptions">
<input type="checkbox" id="1" name="big" value="big"> Big Prints<br>
<input type="checkbox" id="2" name="medium" value="medium" > Medium Prints<br>
<input type="checkbox" id="3" name="small" value="small" > Small Prints<br>
<input type="submit" id="button" value="Submit" onclick="cal()">
</form>
Your comparisons are not correct. A single "=" is not the correct way to compare values you need "==" for truthy and "===" for an exact match.
Change it to
if (document.getElementById("1").checked == true ){
selectionOne = 25;
}
If you need to compare two values in JavaScript you have to use == or === operators:
if (document.getElementById("1").checked == true ){
also you can simplify this if:
if (document.getElementById("1").checked){

form display results under questions + array?

I am having trouble displaying the results on my form under the questions. I thought I had it right. Also I need to create an Array that will hold the answers, which it will randomly pick one, doesnt have to go by the answers. I can't figure out how to display the results on the same page (I have looked and had no luck) Could anyone help me
<!doctype html>
<html>
<?php
include "menu.html"
?>
<head>
<meta charset="UTF-8">
<title>Form</title>
<link href="styles.css" rel="stylesheet">
<script>
function checkForm(){
var chk = true;
var Name = document.getElementById("txt");
var methd= document.getElementById("method");
var rad1= document.getElementById("radM");
var sel= document.getElementById("selM");
var necro = document.getElementById("a");
var guard = document.getElementById("b");
var ele = document.getElementById("c");
var shatter = document.getElementById("imp");
var cor = 0;
Name.style.backgroundColor="#fff";
methd.setAttribute("style", "display:none");
rad1.setAttribute("style", "display:none");
sel.setAttribute("style", "display:none");
if (Name.value==''){
Name.style.backgroundColor = "red";
methd.setAttribute("style", "display:inline");
chk = false;
}
if ((necro.checked==false) && (guard.checked==false) && (ele.checked==false)){
rad1.setAttribute("style", "display:inline");
}
if (shatter.value==0){
selM.setAttribute("style", "display:inline");
}
if (chk==false){
document.getElementById("error").setAttribute("style", "display:inline");
} else {
if (Name.value=="no"){
document.getElementById(txt).innerHTML += 'No';}
if (Name.value=="yes"){
document.getElementById(txt).innerHTML += 'Yes';}
if (ele.checked == true){
document.getElementById(c).innerHTML += 'Elementalist';}
if (necro.checked == true){
document.getElementById(a) += 'Necromancer';}
if (guard.checked == true){
document.getElementById(b) +='Guardian';}
if (shatter.value==1){
document.getElementById(imp) += 'Shatter';
}
if (shatter.value==2){
document.getElementById(imp) += 'Sunless';
}
if (shatter.value==3){
document.getElementById(imp) += 'Claw';
}
style.display = "inline";
innerHTML = "<span>You chose " + imp + txt + " correct!</span>";
}
}
</script>
</head>
<body>
<div class="page">
<article>
<div id="error" class="error"></div>
<h1>What Guild Wars 2 Profession Are You</h1>
<div class="cssTable" style="margin-top:-25px;">
<form method="post" action="thankyou.php" >
<table>
<tr><td colspan="3"></td></tr>
<tr>
<td><div align="right">In Guild Wars 2 Do You Like To Do Damage? </div> </td><td width="217"><input id="txt" name="txt" type="text" size="25"> <br/></td><td><div id="method" style="display:none"><img height="25px" src="purple.png" ></div></td><br/></tr>
<tr>
<td><div align="right">What Best Describes You?</div></td><td>
<input id="a" type="radio" name = "group1" value="A">Healer</input><br/>
<input id="b" type="radio" name = "group1" value="B">One With The Elements</input><br/>
<input id="c" type="radio" name = "group1" value="C">Darkness</input>
</td><td><div id="radM" style="display:none"><img height="25px" src="purple.png"></div></td>
</tr>
<tr>
<td>What One Skill Would You Like To Have?</td>
<td>
<select id="imp"><option value="0" selected="true">Pick A Skill</option>
<option value="1">Stealth</option>
<option value="2">Summon Illusions</option>
<option value="3">Great With A Bow and Arrow</option></select>
</td><td><div id="selM" style="display:none"><img height="25px" src="purple.png"></div></td>
</tr>
<tr><td colspan="3" align="right"><input type="button" class="styled-button-7" value="Send" onclick="checkForm()" /><span id="grde" style="padding-left:25px"> </span></td></tr></table></form></div></article>
</main></div>
</body>
</html>
I moved your call to checkForm() from an onclick on a button to the onsubmit of the form, and started returning chk from checkForm(). You should go through your checkForm() function and start making it work field by field. There are properties that you're trying to access incorrectly.
You can see it at:
http://jsbin.com/homeq/1/

Sum dynamic values from input text and radio

I'm trying to sum the value of an input text changing dynamically with a radio that also changes dynamically. I'm doing something right but also something wrong because it doesn't sum when I want. The sum should show everytime the input text changes and not randomly disappear then you click a radio, just sum them.
the fiddle http://jsfiddle.net/7tFhx/
and the code
<form id="myForm" accept-charset="UTF-8">
<button type="button" class="btn-tt btn-primary btn-lg" disabled>1. Elige el color</button></br>
<label>
<input class="calc" id="fb1" type="radio" name="fb" value="10">
<img src="img/01.jpg"/>
</label>
<label>
<input class="calc" id="fb2" type="radio" name="fb" value="15">
<img src="img/02.jpg"/>
</label>
</br>
</br>
<button type="button" class="btn-tt btn-primary btn-lg" disabled>2. Elige las medidas</button></br>
<div class="row">
<div class="col-xs-2">
ancho (cm.)
<input id="ancho" type="text" class="form-control" placeholder="100">
</div>
<div class="col-xs-2">
alto (cm.)
<input id="alto" type="text" class="form-control" placeholder="100">
</div>
<div class="col-xs-2">
cantidad
<input id="cantidad" type="text" class="form-control" placeholder="1">
</div>
</div>
</br>
<button type="button" class="btn-tt btn-primary btn-lg" disabled>3. Posición mecanismo</button></br>
<label>
<input class="calc" id="fb3" type="radio" name="fb1" value="20">
<img src="img/01.jpg"/>
</label>
<label>
<input class="calc" id="fb4" type="radio" name="fb1" value="35">
<img src="img/02.jpg"/>
</label>
<div>
Total: <span id="price">0</span>€
</div>
</form>
js:
$(function(){
var mecanismoMedida = ['100','200'];
var mecanismoPrecio = ['50','80'];
$('#ancho').on('input',function(){
var j = 1, i = 0;
value = parseInt(($("#ancho").val() / 8) + 1);
for(i = 0; i < mecanismoMedida.length; i++){
if($("#ancho").val() >= mecanismoMedida[i] && $("#ancho").val() <
mecanismoMedida[j]){
value += mecanismoPrecio[i];
break;
} else {
j++;
}
}
$("#price").text(this.value + value);
});
$('#myForm input[type="radio"]').on('change', function () {
var sum = 0;
$("#myForm").find("input[type='radio']:checked").each(function () {
sum += parseInt(this.value);
});
$("#price").text(sum);
});
});
If it's a simple sum you're after, you can simply run an update code on the keyup and change events of all input elements:
$("input").change(function(){update();}).keyup(function(){update();});
To update them, first you need to check and see which one of the two radio buttons are checked and get its value:
function update(){
var p = 0;
for(var i = 0; i < $(".calc").val(); i++)
{
if($($(".calc")[i]).prop("checked") == true)
{
p += parseInt($($(".calc")[i]).val());
}
}
After that, simply parse the values of the textboxes to integers and add them to the value of the radio button. I created a custom function to do this, because if the boxes are empty, parsing them returns NaN:
p = parseInt(p);
p += parseInt(val2($("#ancho")));
p += parseInt(val2($("#alto")));
p += parseInt(val2($("#cantidad")));
p = parseInt(p);
$("#price").html(p);
}
function val2(elm){
if(isNaN(parseInt($(elm).val())))
return 0;
else
return parseInt($(elm).val());
}
JSFiddle

Validation not working on Javascript

I have worked out how to get the alert box up but it seems to skip my other validation which is checking the other feilds, ect, any ideas as too why it is skiiping it? it would really help!
I am fairly new to Javascript and HTML so could you explain it, thank you
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
window.validateForm=function() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
//result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value == "") {
msg += "You must enter the exam Number \n";
document.ExamEntry.subject.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
if (document.ExamEntry.Exam_Number.value.length != 4) {
msg += "You must enter at least Four Numbers in the Exam Number \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var Number = document.ExamEntry.Exam_Number.value
if (isNaN(document.ExamEntry.Exam_Number.value)) {
msg += "You must enter at least four numeric characters in the Exam Number feild \n";
document.ExamEntry.Exam_Number.focus();
document.getElementById('Exam_Number').style.color = "red";
//result = false;
}
var checked = null;
var inputs = document.getElementsByName('Exam_Type');
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (checked == null) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="Exam_Number">Exam Number</td>
<td><input type="text" name="Exam_Number"<font size="1">(Maximum characters: 4)</font> </td>
</tr>
<tr>
<table><form action="">
<td><input type="radio" id="examtype" name="examtype" value="GCSE" /> : GCSE<br />
<td><input type="radio" id="examtype" name="examtype" value="A2" /> : A2<br />
<td><input type="radio" id="examtype" name="examtype" value="AS"/> : AS<br />
<td><input type="submit" name="Submit" value="Submit" onclick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
and here is a jsfiddle
Change:
var inputs = document.getElementsByName('Exam_Type');
to
var inputs = document.getElementsByName('examtype');
It seems you picked the wrong name for the radio elements.
Your for loop was checking the radio buttons incorrectly.
Code:
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
}
}
Please find the working fiddle here http://jsfiddle.net/sDLV4/2/
I changed code here please check...
Please find the working fiddle here
http ://jsfiddle.net/sDLV4/3/
Using HTML5 constraint validation, much of your code can be dropped, see my revision below. In addition to the wrong radio button group name pointed out by Juergen Riemer, your code has the following issues:
Better use the HTML5 DOCTYPE declaration, see below
Instead of <script language="javascript" type="text/javascript"> just use <script>. The script element does not have a language attribute, and the type attribute has the value "text/javascript" by default.
Do not define your validation function on the window object, but rather as global function (as below), or preferably as a member of a namespace object.
Instead of setting the form's name attribute to "ExamEntry", rather set its id attribute and reference the form of a variable like var examForm = document.forms["ExamEntry"];
Your HTML code is not well-formed, because in your form's table, on line 79, you start another table element with another form element, both of which do not have an end tag.
Also, it's preferable to us CSS for the form layout, instead of a table.
In my revision below I'm using a Pure CSS stylesheet for styling forms, and corresponding class values in certain elements.
For more about constraint validation in general and the HTML5 constraint validation features, see this tutorial.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<title>Exam entry</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/combo?pure/0.3.0/base-min.css&pure/0.3.0/forms-min.css" />
<script>
function validateForm() {
var result = true;
var msg = "";
var checked = null;
var examForm = document.forms['ExamEntry'];
var inputs = examForm.examtype;
for (var i = 0; i < inputs.length; i++) {
if (!checked) {
checked = inputs[i];
}
}
if (!checked) {
msg += "Anything for now /n";
} else {
return confirm('You have chosen ' + checked.value + ' is this correct?');
}
if (msg == "") {
return result;
} else {
alert(msg)
return false;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form id="ExamEntry" class="pure-form pure-form-aligned" method="post" action="success.html">
<div class="pure-control-group">
<label for="exNo">Exam Number:</label>
<input id="exNo" name="Exam_Number" required="required" pattern="\d{4}" title="You must enter a 4-digit exam number" />
</div>
<div class="pure-control-group">
<label>Exam type:</label>
<label class="pure-radio"><input type="radio" name="examtype" value="GCSE" /> GCSE</label>
<label class="pure-radio"><input type="radio" name="examtype" value="A2" /> A2</label>
<label class="pure-radio"><input type="radio" name="examtype" value="AS" /> AS</label>
</div>
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onclick="return validateForm();">Submit</button>
<button type="reset" class="pure-button">Reset</button>
</div>
</form>
</body>
</html>

How to add my 2 radio buttons value in jquery?

I have this code:
<div id="star-rating">
<script type="text/javascript">
$(function(){
$('#star-rating form').submit(function(){
$('.test',this).html('');
$('input',this).each(function(){
if(this.checked)
//$('.test',this.form).append(''+this.name+': '+this.value+'<br/>');
$('.test',this.form).append(this.value);
});
return false;
});
});
</script>
<form name="form1" method="post" action="<?=base_url();?>rate/student">
<div class="dbtable">
<table cellpadding="0" cellspacing="0" border="0"><tbody>
<th colspan="4" align="left">Personal Appearance</th>
<tr><td width="10px"></td><td width="60%">Neatness</td>
<td width="20%">
<input name="neat" type="radio" class="neat-star" value="1" title="Poor"/>
<input name="neat" type="radio" class="neat-star" value="2" title="Fair"/>
</td>
</tr>
<tr><td></td><td>Health</td>
<td>
<input name="health" type="radio" class="health-star" value="1" title="Poor"/>
<input name="health" type="radio" class="health-star" value="2" title="Fair"/>
</td>
</tr>
<tr><td></td><td align="right"></td>
<td><input type="submit" value="Submit scores!" /></td>
<td><div class="test Smaller">
<span style="color:#FF0000">Results</span>
</div>
</td></tr>
So now I have 2 radio star rating. What I want is when I click the submit score it will add up the 2 selected radio box. E.g when click radio button neat with the value of 1 and radio button health with the value of 2 then the result will show 3 coz 1+2=3 in my div class=test. Could anyone help me with this.
$('#star-rating form').submit(function() {
$('.test', this).html('');
var total = 0;
$('input', this).each(function(){
if(this.checked) {
total += parseInt(this.value, 10);
}
}
//Do something with total
return false;
});
You need to use parseInt to convert a String into a Number. Otherwise, you'll just be concatenating values onto a string.
$('#star-rating form').submit(function() {
var score = $(this).find('.neat-star').val()
+ $(this).find('.health-star').val();
$(this).find('.test').html(score);
return false;
});
Try this
(function(){
$('#star-rating form').submit(function(){
var neatVal, healthVal;
neathVal = $(this).find("input[name=neat]:checked").val();
healthVal = $(this).find("input[name=health]:checked").val();
$('.test', this).append(praseInt(neatVal) + parseInt(healthVal ));
return false;
});
});

Categories