I want to give each check box an integer value and then if the box is checked add the values and display the total in a text box with the ID="options". So far the code is not sending a value to the desired location. Any instruction on how to improve the code would be helpful. Thank you.
<html>
<body>
<form id="registration" name="registration">
<input name="opt1" value="5" type="checkbox"> Breakfast ($5)
<input name="opt2" value="10" type="checkbox"> Lunch ($10)
<input name="opt3" checked="checked" value="0" type="checkbox"> Happy Hour (free!)
<input id="options" name="options" type="text">
</form>
</body>
</html>
<script>
function getOptions() {
var form = document.getElementById("registration"),
inputs = form.getElementsByTagName("input"),
result = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
result += inputs[i].value;
document.getElementById("options").value = result;
}
}
}
getOptions();
</script>
You may need to attach onchange event handlers to the checkboxes as shown below. And you should parse inputs[i].value to a number using parseFloat() before adding it to result.
var form = document.getElementById("registration"),
inputs = form.getElementsByTagName("input");
function getOptions() {
var result = 0;
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
result += parseFloat(inputs[i].value);
}
}
document.getElementById("options").value = result;
}
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox") {
inputs[i].onchange = function () {
getOptions();
}
}
}
getOptions();
JSFiddle
Related
I have an html page that uses a javascript as a statistical calculator, it just needs to print the results into the text boxes i have displayed, but when i hit my submit button, the screen displays the mean value for a split second. no other fields work or stay.
My html file is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<script src="script.js"></script>
<title>Script Calculator</title>
</head>
<body class="calculator">
<h2 class="stats">Statistical Calculator</h2>
<p> Enter 5-20 values within 0-100 inside the box below.<br>
Each value should be separated by one space.
</p>
<form>
<textarea id="numbers" name="numberarea" rows="4" cols="40"></textarea> <br>
<br>
<input type="submit" id="subbutton" onclick="performStatistics()"
value="Submit">
<input type="reset">
<br><br>
Max: <input type="text" id ="maxnum" name="max" readonly>
<br>
Min: <input type="text" id="minnum" name="min" readonly>
<br>
Mean: <input type="text" id="meannum" name="mean" readonly>
<br>
Median: <input type="text" id="mednum" name="med" readonly>
<br>
Mode: <input type="text" id="modenum" name="mode" readonly>
<br>
Standard Deviation: <input type="text" id="stddev" name="std" readonly>
<br>
Sum: <input type="text" id="sumnum" name="sum" readonly>
<br>
Variance: <input type="text" id="varinum" name="vari" readonly>
<br>
</form>
<hr>
ePortfolio
</body>
</html>
My javascript is as follows:
function performStatistics() {
var newarray = document.getElementById("numbers").value;
var array = newarray.split(" ");
for (var i = 0; i < array.length; i++) {
if (array[i] < 0 || array[i] > 100) {
alert("Enter positive values from 0-100")
return false;
}
}
if (array.length < 5 || array.length > 20) {
alert("Enter at least 5 values & no more than 20");
return false;
}
document.getElementById("meannum").value = calcMean(array);
document.getElementById("mednum").value = calcMedian(array);
document.getElementById("modenum").value = calcMode(array);
document.getElementById("stddev").value = calcStdDev(array);
document.getElementById("sumnum").value = calcSum(array);
document.getElementById("varinum").value = calcVariance(array);
document.getElementById("maxnum").value = findMax(array);
document.getElementById("minnum").value = findMin(array);
return false;
}
function calcMean(array) {
return calcSum(array) / array.length;
}
function calcMedian(array) {
var med = 0;
var arraylen = array.length;
arraylen.sort();
if (arraylen % 2 === 0) {
med = (array[arraylen / 2 - 1] + array[arraylen / 2]) / 2;
//takes average of an even array
} else {
med = array[(arraylen - 1) / 2];
//takes middle value of odd array
}
return med;
}
function calcMode(array) {
var mode = [];
var counter = [];
var i;
var holder;
var maxfreq = 0;
for (i = 0; i < array.length; i += 1) {
holder = array[i];
counter[array] = (counter[holder] || 0) + 1
if (counter[holder] > maxfreq) {
maxfreq = counter[holder];
}
}
for (i in counter)
if (counter.hasOwnProperty(i)) {
//returns boolean value^
if (counter[i] === maxfreq) {
mode.push(Number(i));
//pushes value into (end of) array
}
}
return mode;
}
function calcStdDev(array) {
return Math.sqrt(calcVariance(array)).toFixed(2);
}
function calcSum(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum += Number(array[i]);
}
return sum.toFixed(2);
}
function calcVariance(array) {
var avg = calcMean(array);
var newarray = [];
var vari;
for (i = 0; i < array.length; i++) {
newarray[i] = (array[i] - avg) * (array[i] - avg);
}
vari = calcSum(newarray) / newarray.length;
return vari.toFixed(2);
}
function findMax(array) {
var newarray = array;
var maxnum = Math.max(newarray);
return maxnum;
}
function findMin(array) {
var newarray = array;
var minnum = Math.min(newarray)
return minnum;
}
You need to prevent the submit button from submitting the form.
window.onload=function(){
document.getElementById('subbutton').addEventListener('click', function(ev){
ev.preventDefault(); // prevent the page submit
});
}
You can remove the onclick from the HTML, and add this to your script:
// When the DOM (HTML) is ready
addEventListener('DOMContentLoaded', function() {
// When the form gets submitted (click on submit or enter key)
document.forms[0].addEventListener('submit', function (event) {
performStatistics();
// Prevent the form from refreshing the page
event.preventDefault();
});
});
Note: your script is included in the <head> of your document. Waiting for DOMContentLoaded will ensure the document is ready no matter where your script is called. But you could skip that part if you include your script at the very bottom, before the closing </body> tag.
My for loops are fine and I got the value for both transportationOutput and trasportation2 and I want to check if both values are equal checked the right checkbox input, but it does not get into if condition and I do not know why, I try to replace the == to === but also it does not work
trasportation = "car-train" //value from database
var trasportation2 = document.getElementsByName("transportation");
var transportationOutput = trasportation.split("-");
for (var i = 0; i < transportationOutput.length; i++) {
for (var j = 0; j < trasportation2.length; j++) {
if (trasportation2[j].value == transportationOutput[i]) {
trasportation2[j].checked = true;
}
}
}
<label>transportation</label>
<input type="checkbox" id="localTransportID" name="transportation" value="car"> car
<input type="checkbox" id="localTransportID" name="transportation" value="bus"> bus
<input type="checkbox" id="localTransportID" name="transportation" value="train"> train
<input type="checkbox" id="localTransportID" name="transportation" value="airplane"> airplane
I am trying to design a menu. If you check a box, then sum get added up and if you uncheck it, the sum is reduced. I face trouble in reducing the sum while unchecking the box and also the value of sum is not globally changed. Please help me out.
<head>
<script>
var sum=0;
function a(sum,num) {
sum=sum+num;
document.getElementById("demo").innerHTML=sum;
}
</script>
</head>
<body>
<input type="checkbox" name="Dal" id="dal" onclick=a(sum,10)>Dal<br>
<input type="checkbox" name="Rice" id="rice" onclick=a(sum,20)>Rice<br>
<h1> Total Price is : </h1>
<p id="demo"> 0 </p>
</body>
Change the markup, add a value and a class, and remove the inline JS
<input type="checkbox" name="Dal" id="dal" value="10" class="myClass">Dal
<input type="checkbox" name="Rice" id="rice" value="20" class="myClass">Rice
<h1> Total Price is : </h1><p id="demo">0</p>
Then do
<script type="text/javascript">
var inputs = document.getElementsByClassName('myClass'),
total = document.getElementById('demo');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + add
}
}
</script>
FIDDLE
You can do something like this:
function a (elem, num) {
var k = (elem.checked) ? 1 : -1;
sum = sum + k * num;
document.getElementById("demo").innerHTML = sum;
}
And in the HTML:
<input type="checkbox" name="Dal" id="dal" onclick="a(this, 10);">Dal<br>
<input type="checkbox" name="Rice" id="rice" onclick="a(this, 20);">Rice<br>
Try something like this:
var sum = 0;
function a(id, num) {
if(id.checked == true){
sum += num;
id.onclick = function() { a(id, num)};
}
else {
sum -= num;
id.onclick = function() { a(id, num)};
}
document.getElementById("demo").innerHTML=sum;
}
Fiddle: http://jsfiddle.net/95pvc/2/
My own take would involve removing the event-handling from the HTML (unobtrusive JavaScript) for easier maintenance in future, using data-* attributes to contain the price and using a class-name to identify the relevant ingredients, to give the following HTML:
<input class="ingredients" type="checkbox" name="Dal" data-price="10" id="dal" />Dal
<input class="ingredients" type="checkbox" name="Rice" data-price="20" id="rice" />Rice
<h1> Total Price is : </h1>
<p id="demo">0</p>
Which leads to the following JavaScript:
var ingredients = document.getElementsByClassName('ingredients');
function price() {
var result = document.getElementById('demo'),
curPrice = 0,
ingredients = document.getElementsByClassName('ingredients');
for (var i = 0, len = ingredients.length; i < len; i++) {
if (ingredients[i].checked) {
curPrice += parseFloat(ingredients[i].getAttribute('data-price'));
}
}
result.firstChild.nodeValue = curPrice;
}
for (var i = 0, len = ingredients.length; i < len; i++) {
ingredients[i].addEventListener('change', price);
}
JS Fiddle demo.
To avoid having to iterate through the relevant checkboxes, it might be better to wrap those input elements in a form, and then bind the event-handling to that form:
var ingredients = document.getElementsByClassName('ingredients');
function price() {
var result = document.getElementById('demo'),
curPrice = 0,
ingredients = document.getElementsByClassName('ingredients');
for (var i = 0, len = ingredients.length; i < len; i++) {
if (ingredients[i].checked) {
curPrice += parseFloat(ingredients[i].getAttribute('data-price'));
}
}
result.firstChild.nodeValue = curPrice;
}
document.getElementById('formID').addEventListener('change', price);
JS Fiddle demo.
References:
addEventListener().
element.getAttribute().
getElementsByClassName().
parseFloat().
I'm having a problem trying to create a Javascript function that checks all the checkboxes in a form.
An example of the checkboxes on my form look like
<b>A:</b> <input type="checkbox" name="multipleForms[201][A]"><br>
<b>B:</b> <input type="checkbox" name="multipleForms[201][B]"><br>
<b>C:</b> <input type="checkbox" name="multipleForms[201][C]"><br>
<b>D:</b> <input type="checkbox" name="multipleForms[201][D]"><br>
<b>A:</b> <input type="checkbox" name="multipleForms[500][A]"><br>
<b>B:</b> <input type="checkbox" name="multipleForms[500][B]"><br>
<b>C:</b> <input type="checkbox" name="multipleForms[500][C]"><br>
And what I want to do is be able to pass a number such as 201 and 500 into a Javascript function and have all checkboxes with the first array index as that integer be checked.
So, checkAll(201) would have the first 4 checkboxes checked and checkAll(500) would have the other 3 checkboxes checked.
I would rather not change the names of my checkboxes if that is possible as the stringed indexes are really important for my PHP code.
Thanks in advance.
Also, I would rather have non-jQuery code.
Something like that ? : http://jsfiddle.net/RZPNG/6/
var checkboxes = document.getElementsByTagName('input');
function check(num) {
for (var i = 0; i < checkboxes.length; i++) {
if (parseInt(checkboxes[i].name.split('[')[1]) === num) {
checkboxes[i].checked = 'checked';
}
}
}
check(201);
Something like the following should do:
function checkBoxes(form, s) {
var input, inputs = form.getElementsByTagName('input');
var re = new RegExp(s);
for (var i=0, iLen=inputs.length; i<iLen; i++) {
input = inputs[i];
if (input.type == 'checkbox' && re.test(input.name)) {
input.checked = true;
} else {
input.checked = false;
}
}
}
You could also use querySelectorAll, but support isn't that common yet:
function checkBoxes(s) {
var els = document.querySelectorAll('input[name*="' + s + '"]');
for (var i=0, iLen=els.length; i<iLen; i++) {
els[i].checked = true;
}
}
Is there a quick way or function that would tell me true/false if all check boxes are deselected? Without going through array? (with JS and HTML)
All my check boxes have the same name...
<form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
<input type=checkbox name="us" value="Joe" ID="Checkbox1">
<input type=checkbox name="us" value="Dan" ID="Checkbox2">
<input type=checkbox name="us" value="Sal" ID="Checkbox3">
</form>
jQuery would be a mass of unneeded bloat for a task this trivial. Consider using it if you are running it for other purposes, but all you need is something like this:
function AreAnyCheckboxesChecked () {
var checkboxes = document.forms.Form2.elements.us;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
You have to loop through them. Even a library like jQuery will loop through them, just hide it from you.
var form = document.getElementById('Form2');
var inputs = form.getElementsByTagName('input');
var is_checked = false;
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type == 'checkbox' && inputs[x].name == 'us') {
is_checked = inputs[x].checked;
if(is_checked) break;
}
}
// is_checked will be boolean 'true' if any are checked at this point.
JavaScript:
var allischecked = (function(){
var o = document.getElementById("Form2").getElementsByTagName("input");
for(var i=0,l=o.length;i<l;i++){
o[i].type === "checkbox" && o[i].name === "us" && o[i].checked || return false;
}
return true;
})();
With jQuery:
var allischecked = ($("#Form2 input:checkbox:not(checked)").length === 0);
In summary, this snipped will return true if all are NOT checked. It bails out as soon as a checked one is found.
var a = document.getElementsByName("us");
for(var i=0; i<a.length; i++)
if(a[i].checked)
return false;
return true;
(did not test, but conceptually it is valid)
What do you mean by
Without going through array
?
You could just do
function check() {
var anyChecked = false;
var form = document.getElementById('Form2');
var checkboxes = form.getElementsByTagName('input');
for(var i=0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
anyChecked = true;
break;
}
}
alert("Checkboxes checked? " + anyChecked);
}
Working Demo
If you have a large amount of checkboxes that you don't want to loop through to test it might be more efficient to use this approach.
var checked = 0;
$("input[type=checkbox]").live("click", function() {
if($(this).attr("checked")) checked++;
else checked--;
}
Then you would be able to test like this.
if(checked === 0) {
doSomething();
}
The proper solution with jQuery attribute checked:
$checkboxes = $('#Form2 input:checkbox');
$checkboxes.on('click', checkboxes);
function checkboxes() {
var allChecked = $checkboxes.not(':checked').length == 0;
console.log(allChecked);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
<input type=checkbox name="us1" value="Joe" ID="Checkbox1"><label>Joe</>
<input type=checkbox name="us2" value="Dan" ID="Checkbox2"><label>Dan</>
<input type=checkbox name="us3" value="Sal" ID="Checkbox3"><label>Sal</>
</form>
Even easier without loop
const toggleCheckboxes = checkbox => {
if(checkbox.checked){
return true
}else{
if(document.querySelectorAll(':checked').length === 0){
// All are unchecked
return false
}
}
}