Javascript - How to get the sum of a checkbox group - javascript

I'm trying to get the sum of my checkbox group (from database):
<script type="text/javascript">
$.ajax({
// SOME CODE HERE
$("#permisos01Div").append("<input type='checkbox' name='chk_permisos'
onClick='VerCostoPermiso()' value='"+data[i].costo+"' > " +
data[i].permiso + "<br>");
// SOME CODE HERE
});
function VerCostoPermiso(){
var group = document.getElementById('chk_permisos');
var sum = 0.00;
for (var i=0; i<group.length; i++){
if (group[i].checked == true){
sum = sum + parseFloat(group[i].value);
}
}
alert(sum);
}
</script>
The result should be: Every time i check the box, alert the sum of the total cbs checked.
My code doesn't work, i really don't know where is the problem.
Thank you for answers

It looks like your dont have an ID assigned, but your using getElementById. Try getElementsByName.

Seems you're using jQuery, you also have a name attribute, not an ID:
var sum = 0;
$(":checkbox:checked[name=chk_permisos]").each(function() {
sum += parseFloat(this.value);
});

"chk_permisos" is the value of a name attribute and should be selected with documents.getElementsByName("chk_permisos"):
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function VerCostoPermiso() {
var group = document.getElementsByName("chk_permisos");
var sum = 0.00;
for (var i = 0; i < group.length; i++) {
if (group[i].checked == true) {
sum = sum + parseFloat(group[i].value);
}
}
alert(sum);
}
</script>
</head>
<body>
<div id="permisos01Div">
<input type='checkbox' name='chk_permisos' onClick='VerCostoPermiso()' value='1'>A1<br>
<input type='checkbox' name='chk_permisos' onClick='VerCostoPermiso()' value='10'>B10<br>
<input type='checkbox' name='chk_permisos' onClick='VerCostoPermiso()' value='100'>C100<br>
</div>
</body>
</html>

If there is a checkbox with out a value sometimes it has the value of "on". When you put this through the parseFloat function you get an error. I would add a number check to the if statement.
if (group[i].checked == true && group[i].value*0 == 0);

Related

How to get the proper Javascript output for the number pyramid

I am currently working on a 1/2 pyramid of numbers. I can get the output to total up the line and get everything but the * sign between the numbers. Hoping that someone out there can lend a helping hand. Here is the code that I have completed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Assignment 1</title>
<script>
var num = "";
var match ="";
var size = prompt("Enter the size of the pyramid");
if (size >=1) {
var total="1";
for(var i=1; i<=size; i++)
{
if (i < size){
num = num + i + " "
} if (i==size) {
num =num + i }
total= total * i;
document.write(num + " = "+ total + "<br>");
}
}else {
alert("Please enter a number equal to or greater than 1");
}
var total="1";
</script>
</head>
<body>
<main>
<!-- Will show after the script has run -->
<h1>Assignment 1</h1>
</main>
</body>
</html>
-
I am looking for output like this
1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120
and so on.
Thanks again
You can use a loop like this and make the total time the new iteration value:
var total = 1;
var newList = [];
for(let i=1; i<=5; i++) {
newList.push(i);
total *= i;
console.log(newList.join('*') + '=' + total)
}
Run code snippet output:
1=1
1*2=2
1*2*3=6
1*2*3*4=24
1*2*3*4*5=120

JavaScript function inside HTML display in browser

I have a problem regarding my JavaScript code. I'm trying to output the sum in the browser, but it doesn't work. I tried every way of displaying the message in JavaScript: console.log(), document.write(), document.getElementById(). None of this seems to work. My code looks okay, but it simply won't output anything. Can someone help me, please?
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script type="text/javascript">
var sum = 0;
for(var i = 0; i < 1000; i++){
if(i%3 === 0 || i%5 === 0)
{
sum += i;
}
console.log('The sum is' + " " +sum);
}
</script>
</head>
</html>
This code works fine here. I'm running IE11 and the sum displays in the console with no problem. See the snippet below; nothing has been changed.
Maybe you just need to open the dev console? F12 in IE/Edge, or Settings > Developer Tools > Console in Chrome (I think).
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script type="text/javascript">
var sum = 0;
for (var i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
console.log('The sum is' + " " + sum);
}
</script>
</head>
</html>
If you want to have your code output to the browser window, you could do something like this, where you add the result to the DOM:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
</head>
<body>
<div id='resultsDiv'>
<h3>Results Here:</h3>
</div>
<script type="text/javascript">
var sum = 0;
var resultsDiv = document.getElementById('resultsDiv');
for (var i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
resultsDiv.innerHTML += 'The sum is' + " " + sum + "<br />";
}
</script>
</body>
</html>
Well, you wrote that you want to display in the browser, I assume you mean the viewport
First of all, you need a body tag:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head></head>
<body></body>
</html>
Sure, the Javascript can be inside the HEAD tag, but if you want anything to be displayed, it needs to be inside the BODY tag.
Second, console.log will print the result to the console, if you want to print the sum in the body, you should change the "print" part to something like
document.getElementsByTagName('body').innerHTML = 'The sum is' + " " + sum;
Or
document.getElementById('sum').innerHTML = 'The sum is' + " " + sum;
Where sum will be an id attribute added to the body tag, also, the
<meta charset="UTF-8">
Goes inside the HEAD tag, and last but not least, you are executing the javascript right away and the DOM won't be necessarily loaded, I suggest you create a javascript function to be called onload as an attribute in the body tag.
So, a working implementation could be like this:
function sum(){
var sum = 0;
for (var i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
console.log('The sum is' + " " + sum);
}
document.getElementById('sum').innerHTML = 'The sum is ' + sum
}
<body id="sum" onload="sum()"></body>
The code will look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function sum(){
var sum = 0;
for (var i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum += i;
}
console.log('The sum is' + " " + sum);
}
//document.getElementsByTagName('body').innerHTML = 'The sum is ' + sum
document.getElementById('sum').innerHTML = 'The sum is ' + sum
}
</script>
</head>
<body id="sum" onload="sum()"></body>
</html>

javascript - how to use a text box input in a for loop

I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example
function games() {
var num = document.getElementById("inp").vale;
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
You have a typo. It's .value.
You can convert a string to a number by using * 1.
Something like this:
function games() {
var num = document.getElementById("inp").value * 1; // Convert the string value a number.
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
function roll_dice() {
console.log("Test.");
}
var btnRun = document.getElementById("btnRun");
btnRun.onclick = function() {
games();
};
<input id="inp" type="text" />
<button id="btnRun" type="button">Run</button>
The value you get from input box is string you need to convert it into int . If you are using int in loop .
var num = parseInt(document.getElementById("inp").value);
function games() {
var num = document.getElementById("inp").value;
var i;
for (i = 0; i < Number(num); i++) {
roll_dice();
}
}
**<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>
</body>
</html>
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>**

Storing multiple values with different id in array - php,javascript

Multiple values are inputted using below code:
$c_num is the count of inputs. There are n number of inputs
$stud['stud_c'] is student codes, S01,S02,S05,S08,S19 .........
On a javascript function calculate(), a portion of id is passed.
code:
<input type="number" required id="c_m_<?php echo $c_num; ?>_<?php echo $stud['stud_c'];?>" name="c_m_<?php echo $c_num; ?>[<?php echo $stud['stud_c'];?>]" onkeypress="calculate('<?php echo $c_num; ?>_<?php echo $stud['stud_c'];?>','<?php echo $stud['stud_c'];?>')" class="num<?php echo $c_num; ?> " >
When I alert class1, i am getting corresponding output. But how to store multiple values with different id in array? How to store those inputted values in array num[] ? I also want to alert the total of these inputs.
Corresponding script for finding sum of n number of inputs:
function calculate(class1,class2){
var n = parseFloat(document.getElementById('count').value);
var num[] = parseFloat(document.getElementById('c_m_'+class1).value);
var total=0;
for (var i = 0; i <n; i++) {
total = total + parseFloat(num[i]) ;
}
if (!isNaN(total)) {
document.getElementById('total_mark_'+class2).value = Math.round(total);
}
}
Try like this..
<script>
arr =[];
function calculate(class1)
{
//var n = parseFloat(document.getElementById('count').value);
var num = parseFloat(document.getElementById('c_m_'+class1).value);
arr.push(num);
var total=0;
var n =arr.length;
for (var i = 0; i <n; i++) {
total = total +arr[i];
}
alert(total);
}
</script>
Try this . array.push().And array declaration was wrong.use num=[] instead of num[] .
I don't know why use n on forloop length. if you originaly need the array length use with n=num.length
var num=[];
function calculate(class1)
{
var n = parseFloat(document.getElementById('count').value);
num.push(parseFloat(document.getElementById('c_m_'+class1).value));
var total=0;
//n=num.length if you need num array length use this
for (var i = 0; i <n; i++) {
total = total + parseFloat(num[i]) ;
}
alert(total);
}
Assign a common attribute for the inputs and fetch them by this attribute. There are many ways to fetch nodes by attribute. To name a few:
parentNode.getElementsByClassName('className') fetches all the child nodes having specific class attribute;
parentNode.querySelectorAll('input[attribute="value"]') fetches a node list of all input tags having specific attribute value
using jQuery selector like 'input[attribute="value"]'
Example
(function() {
var inputs, i, total = 0;
inputs = document.forms.c.querySelectorAll("input[name='c_m[]']");
for (i = 0; i < inputs.length; i++) {
total += Number(inputs[i].value);
}
console.log(total);
})();
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>XXX</title>
</head>
<body>
<form name="c">
<input type="text" name="c_m[]" value="1" size="3" />
<input type="text" name="c_m[]" value="2" size="3" />
<input type="text" name="c_m[]" value="3" size="3" />
</form>
</body>
</html>
Note, you don't need to collect the input values into num array, if you only want to compute the sum of the values. Simply literate the nodes and collect their values. If for some reason you still want to collect the values into an array, use Array.prototype.push method:
var num = [];
for (i = 0; i < inputs.length; i++) {
num.push(inputs[i].value);
}
<script type="text/javascript">
var RECALCULATE = function(a,b) {
var rowtotal = 0;
n = new Array();
var count = document.getElementById('criteria_count').value;
for (i = 1; i <=count; i++) {
if (parseInt(document.getElementById('criteria_mark_'+i+'_'+b).value) > 0) {
n[i] = parseInt(document.getElementById('criteria_mark_'+i+'_'+b).value);
rowtotal += n[i];
}
}
document.getElementById('total_mark_'+b).value = rowtotal;
};
</script>

The fifteen puzzle game

I am doing a fifteen puzzle game and I want that you only can click on a number next to the empty box, but now you can click everywhere...how to change this? I have thought that you can make an if- statement for columns and rows..
<!DOCTYPE html>
<html>
<head>
<title>The Fifteen Puzzle Game</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var currentBoard = new Array(' ','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15');
for(i=0 ; i++<100 ; x = Math.floor(Math.random()*16), y = Math.floor(Math.random()*16), currentBoard[x] = currentBoard.splice(y, 1, currentBoard[x])[0]);
repaint(); // Redraw puzzle board
//
// Funktion repaint()
// Redraw puzzle board
function repaint(){
currentString = "";
for(i=1;i<17;i++){
currentString += "<input type='button' id='" + i + "' value='" + currentBoard[i-1] + "' />";
if ( (i%4) == 0 ) currentString += "<br />";
}
$("#board").html(currentString);
}
function swapArrElems(index_a, index_b) {
var temp = currentBoard[index_a];
currentBoard[index_a] = currentBoard[index_b];
currentBoard[index_b] = temp;
}
$('#board').click(function(event){
current = $(event.target).attr("id")-1;
for(i=0;i<16;i++) if( currentBoard[i]==0 ) zeroIndex = i;
swapArrElems(current, zeroIndex);
repaint();
});
});
</script>
<style>
input[type="button"] { width: 80px; height: 80px; font-size: 30px; }
</style>
</head>
<body>
<div id="board">
</div>
</body>
</html>
From the way I understood your code, you have 16 buttons id'ed by rows of 4. Each time a button is clicked, the array value of that button and the blank button swap. You're almost there. The detail that is the most important here is the button ID's, which stay the same throughout.
You need to add a comparison between the ID of the clicked button, and that of the blank button, which requires a conditional.
I'm not going to provide the code for you, because I don't want to just give away the answer. I'm going to give you the logic instead:
In your last function, after if( currentBoard[i]==0 ) zeroIndex = i;
**Else if** the id(clicked button) == id(blank button)-1. OR id(blank button)+1. OR
id(blank button)-4. OR id(blank button)+4 ........
Swap the elements.
Else
don't swap the elements.
Good luck! Hope this helps.
for (i = 0; i < 16; i++) {
if (currentBoard[i] == 0) {
if ((i - current) == 4 || (current - i) == 4 || (current - i) == 1 || (i - current) == 1) {
zeroIndex = i;
swapArrElems(current, zeroIndex);
repaint();
}
}
}

Categories

Resources