Run javascript on multiple selected checkboxes - javascript

Hello I am currently writing a web application that calculates a number based on what a user has checked.
You can see it here.
If you go to the link you can see that a person will check a checkbox first and enter a value from the dropdown and type 2 values to get an output.
What I need help with is being able to calculate the value for more than one checkbox at a time.
Right now I can only calculate the value for a checkbox one at a time even if multiple are selected. So basically I need help try to figure how to calculate for more than one checkbox at a time.
I was using an if statement inside my javascript file but thats not giving me the result that I want.

Just remove else if statements, change for IF only. But I have to say that's solution its not that scalable, and for a big application could turns into a nightmare.
I recommend you try to use $("input:checked").each(function() {}); if you dont want to store it and just show the values on the client to avoid further problems and bad code. With your line of thought, you'll need everytime make copy and paste those IF's everytime you want to implement new form labels.
$(document).ready(function(){
function check(){
if($('#checkbox1').is(':checked')){
var pokemonCount = parseInt($("#pokecount1").val());
var candyCount = parseInt($("#candycount1").val());
var reqCandy = parseInt($("#dropdown1 :selected").val());
var evolveAmount = 0;
evolveAmount = Math.floor(((candyCount + pokemonCount) - 1) / (reqCandy));
$("#p1").html(evolveAmount);
}
if($('#checkbox2').is(':checked')){
var pokemonCount2 = parseInt($("#pokecount2").val());
var candyCount2 = parseInt($("#candycount2").val());
var reqCandy2 = parseInt($("#dropdown2 :selected").val());
var evolveAmount2 = 0;
evolveAmount2 = Math.floor(((candyCount2 + pokemonCount2) - 1) / (reqCandy2));
$("#p2").html(evolveAmount2);
}
if ($('#checkbox3').is(':checked')){
var pokemonCount3 = parseInt($("#pokecount3").val());
var candyCount3 = parseInt($("#candycount3").val());
var reqCandy3 = parseInt($("#dropdown3 :selected").val());
var evolveAmount3 = 0;
evolveAmount3 = Math.floor(((candyCount3 + pokemonCount3) - 1) / (reqCandy3));
$("#p3").html(evolveAmount3);
}
}
$("#compute").click(function(){
check()
});
});

Just remove Else if to if only
$(document).ready(function(){
function check(){
if($('#checkbox1').is(':checked')){
var pokemonCount = parseInt($("#pokecount1").val());
var candyCount = parseInt($("#candycount1").val());
var reqCandy = parseInt($("#dropdown1 :selected").val());
var evolveAmount = 0;
evolveAmount = Math.floor(((candyCount + pokemonCount) - 1) / (reqCandy));
$("#p1").html(evolveAmount);
}
if($('#checkbox2').is(':checked')){
var pokemonCount2 = parseInt($("#pokecount2").val());
var candyCount2 = parseInt($("#candycount2").val());
var reqCandy2 = parseInt($("#dropdown2 :selected").val());
var evolveAmount2 = 0;
evolveAmount2 = Math.floor(((candyCount2 + pokemonCount2) - 1) / (reqCandy2));
$("#p2").html(evolveAmount2);
}
if ($('#checkbox3').is(':checked')){
var pokemonCount3 = parseInt($("#pokecount3").val());
var candyCount3 = parseInt($("#candycount3").val());
var reqCandy3 = parseInt($("#dropdown3 :selected").val());
var evolveAmount3 = 0;
evolveAmount3 = Math.floor(((candyCount3 + pokemonCount3) - 1) / (reqCandy3));
$("#p3").html(evolveAmount3);
}
}
$("#compute").click(function(){
check()
});
});

You've used elseif, so if the first checkbox is checked then it runs that code and stops. You need a series of if blocks:
if(1.isChecked){
}
if(2.isChecked){
}

You are using else if statements in your code, which means that the code of only one of the 3 if statements can be executed. More info here.
You need to replace them with simple if statements, like this:
$(document).ready(function(){
function check(){
if($('#checkbox1').is(':checked')){
var pokemonCount = parseInt($("#pokecount1").val());
var candyCount = parseInt($("#candycount1").val());
var reqCandy = parseInt($("#dropdown1 :selected").val());
var evolveAmount = 0;
evolveAmount = Math.floor(((candyCount + pokemonCount) - 1) / (reqCandy));
$("#p1").html(evolveAmount);
}
if($('#checkbox2').is(':checked')){
var pokemonCount2 = parseInt($("#pokecount2").val());
var candyCount2 = parseInt($("#candycount2").val());
var reqCandy2 = parseInt($("#dropdown2 :selected").val());
var evolveAmount2 = 0;
evolveAmount2 = Math.floor(((candyCount2 + pokemonCount2) - 1) / (reqCandy2));
$("#p2").html(evolveAmount2);
}
if ($('#checkbox3').is(':checked')){
var pokemonCount3 = parseInt($("#pokecount3").val());
var candyCount3 = parseInt($("#candycount3").val());
var reqCandy3 = parseInt($("#dropdown3 :selected").val());
var evolveAmount3 = 0;
evolveAmount3 = Math.floor(((candyCount3 + pokemonCount3) - 1) / (reqCandy3));
$("#p3").html(evolveAmount3);
}
}
$("#compute").click(function(){
check()
});
});

Related

Generate .click functions inside for loop

Inside my for loop that loops through 15 "box" objects, code below:
for (var i = 0; i < boxesLength; i++) {
I'm trying to generate these click events automatically, they used to be like this: (all the way up until 15)
$("#box0").click(function(){
var rw = 462;
var input = $('#rw');
input.val(rw);
var rh = 310;
var input = $('#rh');
input.val(rh);
calculateRectangle();
calculateRectangle2();
});
Right now I am trying to auto-generate these in the for loop by doing this:
$("#box" + i).click(function(){
var rw = allBoxes[i].width;
var input = $('#rw');
input.val(rw);
var rh = allBoxes[i].length;
var input = $('#rh');
input.val(rh);
calculateRectangle();
calculateRectangle2();
});
What am I doing wrong? When I console log "#box" + i I am getting the expected result..
This is an exemple of closures. When you're trying to click one button then your alghorithm will use the last value of i variable which is boxesLength.
To solve this, just use letkeyword.
for (let i = 0; i < boxesLength; i++) {
^^^
Another solution will be like this:
$("#box" + i).click(function(i){
return function(){
var rw = allBoxes[i].width;
var input = $('#rw');
input.val(rw);
var rh = allBoxes[i].length;
var input = $('#rh');
input.val(rh);
calculateRectangle();
calculateRectangle2();
}}(i));

Cant call Jquery function in if loop

my first ever question pretty sure I'm being a bit daft here, but am a beginner and would appreciate your help.
Im working on a webpage where there is a html table listing several columns of data.
When the page loads it runs a jquery script which counts the different types of "incidents" and plots them in another table which then another jquery script populates a graph.
I have a third script (javascript) which after a button is clicked, runs an if loop, which looks at the data in the first column and if it does not match the criteria then the row is deleted.
So far so good, the issue is that I want the script which populates the table for the graph to run again, but Im not sure how to call it from my if loop.
Ive put the two scripts below, basically I want to call the 1st script in the second script.
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')");
$("#result").html(NumFireAlarms.length + " Fire Alarm");
var firealarms = NumFireAlarms.length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = firealarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')");
$("#result").html(NumLockout.length + " Lockout Out of Office Hours");
var lockouts = NumLockout.length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = lockouts
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')");
$("#result").html(NumLockout.length + " Lockout Day Time");
var lockoutsDayTime = NumLockoutDayTime.length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = lockoutsDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')");
$("#result").html(NumSensitiveIncident.length + " Sensitive Incident");
var SensitiveIncident = NumSensitiveIncident.length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = SensitiveIncident
});
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var start_date = document.getElementById("start_date").value;
var end_date = document.getElementById("end_date").value;
var staff_type = document.getElementById("Job_Title").value;
var i;
var count = 0;
var table_length = document.getElementById("incidents").rows;
var TL = table_length.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
var date_column = document.getElementById("incidents").rows[i].cells.item(1).innerHTML;
var staff_colunm = document.getElementById("incidents").rows[i].cells.item(8).innerHTML;
if (category_column === incident_category)
{
alert("yay")
count++
}
else if (category_column !== incident_category)
{
alert("boo")
document.getElementById("incidents").deleteRow(i);
//CALL FIRST SCRIPT HERE??
}
}
}
I removed a few bits of code that did not seem to do anything, but I'm sure you can put them back. I think you might want something like this:
function updateTable(){
var elResult = document.getElementById("result");
var elNumIncidentType = document.getElementById("no_of_incident_type");
var firealarms: document.querySelectorAll("#incidents tr:contains('Fire Alarm')").length;
var lockouts: document.querySelectorAll("#incidents tr:contains('Lockout Out of Office Hours')").length;
var lockoutsDayTime: document.querySelectorAll("#incidents tr:contains('Lockout Day Time')").length;
var sensitiveIncident: document.querySelectorAll("#incidents tr:contains('Sensitive Incident')").length;
elResult.innerHTML = "";
elResult.innerHTML += "<div>" + firealarms + " Fire Alarm</div>";
elResult.innerHTML += "<div>" + lockouts + " Lockout Out of Office Hours</div>";
elResult.innerHTML += "<div>" + lockoutsDayTime + " Lockout Day Time</div>";
elResult.innerHTML += "<div>" + sensitiveIncident + " Sensitive Incident</div>";
elNumIncidentType.rows[1].cells[1].innerHTML = firealarms;
elNumIncidentType.rows[2].cells[1].innerHTML = lockouts;
elNumIncidentType.rows[3].cells[1].innerHTML = lockoutsDayTime;
elNumIncidentType.rows[4].cells[1].innerHTML = sensitiveIncident;
}
function filterForGraph() {
var elIncidents = document.getElementById("incidents");
var incident_category = document.getElementById("Incident_Category").value;
var table_length = document.getElementById("incidents").rows.length;
for (var i = table_length - 1; i >= 1; i--) {
var currentIncident = elIncidents.rows[i].cells;
var category_column = currentIncident.item(0).innerHTML;
if (category_column != incident_category) { elIncidents.deleteRow(i); }
}
updateTable();
}
$(function(){ updateTable(); });
Hi JonSG tried your code and it didnt work not sure why, but it gave me some ideas to work with and I think Ive cracked it
function Populate_Incident_No_Table() {
//previously function called updateTable
$(function () {
var NumFireAlarms = $("#incidents tr:contains('Fire Alarm')").length;
document.getElementById("no_of_incident_type").rows[1].cells[1].innerHTML = NumFireAlarms
var NumLockout = $("#incidents tr:contains('Lockout Out of Office Hours')").length;
document.getElementById("no_of_incident_type").rows[2].cells[1].innerHTML = NumLockout
var NumLockoutDayTime = $("#incidents tr:contains('Lockout Day Time')").length;
document.getElementById("no_of_incident_type").rows[3].cells[1].innerHTML = NumLockoutDayTime
var NumSensitiveIncident = $("#incidents tr:contains('Sensitive Incident')").length;
document.getElementById("no_of_incident_type").rows[4].cells[1].innerHTML = NumSensitiveIncident
});
}
function filterForGraph() {
var incident_category = document.getElementById("Incident_Category").value;
var i;
var TL = document.getElementById("incidents").rows.length;
for (i = TL - 1; i >= 1; i--)
{
var category_column = document.getElementById("incidents").rows[i].cells.item(0).innerHTML;
if (category_column !== incident_category)
{
document.getElementById("incidents").deleteRow(i);
}
}
Populate_Incident_No_Table();
drawGraph();
}
I think the issue was how I was trying to call the functions. So what I've done to achieve what I wanted (please excuse any bad terminology / phrasing).
First I tried to name the function $(function updateTable(){ this did not work when I then tried to call the function like this updateTable();
Second thing I tried was putting the updateTable() function "inside" a function and call that function. This has worked for me I dont know why.
Thanks for your help without it I would not have thought to try what I did

Javascript- Dynamic variable loop

I'm trying to reduce the amount of code I repeat.
Currently I have the below:
var item1H = $(".item-1").height();
var item1W = $(".item-1").height();
$(".item-1 .text").css('margin-left', -item1W/2);
$(".item-1 .text").css('margin-bottom', -item1H/2);
var item2H = $(".item-2").height();
var item2W = $(".item-2").height();
$(".item-2 .text").css('margin-left', -item2W/2);
$(".item-2 .text").css('margin-bottom', -item2H/2);
I'm looking to put this into a for loop where the variable number would count up to whatever number I needed it to stop.
You can make function like this and use whenever you want
toSetMargin(".item-2")
toSetMargin(".item-2")
function toSetMargin(objStr){
var widthTmp = $(objStr + ' .text').height();
var heightTmp = $(objStr + ' .text').height();
obj.css('margin-left', -widthTmp/2);
obj.css('margin-bottom', -heightTmp/2)
}
This code not impact any other code.
You could use $('[class^="item-"]') to get all the elements that have a class that starts with item-, and the loop over them
$('[class^="item-"]').each(function(){
var $elem = $(this);
var item1H = $elem.height();
var item1W = $elem.width();
$elem.find('.text').css({'margin-left': -item1W/2,'margin-bottom':-item1H/2});
});
Ooh boy, one of these problems. This should help (untested):
for(i=1;i<=STOPPING_NUMBER;i++){
window["item"+i+"H"] = $(".item-"+i).height();
window["item"+i+"W"] = $(".item-"+i).width(); //Was height, accident?
$(".item-"+i+" .text").css('margin-left', 0-window["item"+i+"W"]/2); //Hope this works lol
$(".item-"+i+" .text").css('margin-bottom', 0-window["item"+i+"H"]/2);
}
Guessing these lines:
var item1W = $(".item-1").height();
var item2W = $(".item-2").height();
Should have been:
var item1W = $(".item-1").width();
var item2W = $(".item-2").width();
You could do something like:
function setCSS(item,attr,val) {
$(item +" .text").css(attr, (val * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,"margin-left",$(".item-"+ i).width());
setCSS(".item-"+ i,"margin-bottom",$(".item-"+ i).height());
}
Or something less flexible within the function:
function setCSS(item,w,h) {
$(item +" .text").css("margin-left", (w * -1)/2);
$(item +" .text").css("margin-bottom", (h * -1)/2);
}
var i, max = 10;
for(i=1;i<=max;i++) {
setCSS(".item-"+ i,$(".item-"+ i).width()),$(".item-"+ i).height());
}
Something like this should be pretty acceptible in your case, I guess:
for (var i = 1, len = someN; i < len; i++) {
var $item = $('.item-' + i);
$item.find('.text').css({
'margin-left': -$item.width() / 2,
'margin-bottom': -$item.height() / 2
});
}

Unexpected break in nested loop doesn't show up in debugger

The purpose of the code is to build a series of nested HTML using information in objects:
Here are the informational objects I created:
function branch(level,sciname,comname,parent,children){
this.level = level;
this.sciname = sciname;
this.comname = comname;
this.parent = parent;
this.children = children;}
var animalia = new branch(1,'Animalia','Animals',"",['chordata']);
var chordata = new branch(2,'Chordata','Chordates',animalia,['petromyzontida','actinopterygii']);
var actinopterygii = new branch(3,'Actinopterygii','Ray-finned Fishes',chordata,['siluriformes','scorpaeniformes','salmoniformes','percopsiformes','perciformes','osteoglossiformes','osmeriformes','lepisosteiformes','gasterosteiformes','gadiformes','esociformes','cyprinodontiformes','cypriniformes','clupeiformes','atheriniformes','anguilliformes','amiiformes','acipenseriformes']);
var petromyzontida = new branch(3,'Petromyzontida','Lampreys',chordata,['petromyzontiformes']);
And here is the script:
function CreateDiv(parent,child,z,width,height,top,left,bgcolor){
var parent_ = document.getElementById(parent);
var newdiv = document.createElement("div");
newdiv.setAttribute("id",child);
newdiv.style.zIndex = z;
newdiv.style.position = "absolute";
newdiv.style.width = width + "%";
newdiv.style.height = height + "%";
newdiv.style.top = top + "%";
newdiv.style.left = left + "%";
newdiv.style.backgroundColor = bgcolor;
parent_.appendChild(newdiv);}
function CreateTree(){
var firstdiv = document.createElement("div");
firstdiv.setAttribute("id","animalia");
document.getElementById("container1").appendChild(firstdiv);
var parent1 = "animalia";
var children1 = window[parent1].children;
var numbchildren1 = children1.length;
var rowcounter1 = 1;
var columncounter1 = 0;
for (i=0;i<numbchildren1;i++){
var child1 = children1[i];
var z1 = 2;
var columns1 = Math.ceil(Math.sqrt(numbchildren1));
var width1 = (100/columns1) - 2;
var rows1 = Math.ceil(numbchildren1/columns1);
var height1 = (100/rows1) - 2;
var top1 = rowcounter1*height1 - height1 + 1;
var left1 = columncounter1*width1 + 1;
var bgcolor1 = "#B43333";
CreateDiv(parent1,child1,z1,width1,height1,top1,left1,bgcolor1);
var numbchildren2 = window[child1].length;
if ((i/rowcounter1) == columns1){
rowcounter1 = rowcounter1 + 1;}
else {rowcounter1 = rowcounter1;}
if (columncounter1 == columns1){
columncounter1 = 1;}
else {columncounter1 = columncounter1 + 1;}
var rowcounter2 = 1;
var columncounter2 = 0;
console.log("before:" + columncounter2);
for (j=0;j<numbchildren2;j++){
console.log("after:" + columncounter2);
var child2 = children2[j];
var z2 = 3;
var columns2 = Math.ceil(Math.sqrt(numbchildren2));
var width2 = (100/columns2) - 1;
var rows2 = Math.ceil(numbchildren2/columns2);
var height2 = (100/rows2) - 1;
var top2 = rowcounter2*height2 - height2 + 1;
var left2 = columncounter2*width2 - width2 + 1;
var bgcolor2 = "#B48233";
CreateDiv(parent2,child2,z2,width2,height2,top2,left2,bgcolor2);}}}
I've run the code through a debugger dozens of times and I get no errors. Yet the script does not fully execute. I suspected an infinite loop but I fail to see why that would occur and after going over the code in great detail, I can find no real problems. I can tell where the code seems to break. There are two console.log() statements in the above code. The first console statement gets properly logged, but the second one does not. The debugger shows no errors (Firebug), but the code still fails to fully execute. Please help! And suggestions or criticism will be very welcome as I'm still learning some of the basics.
As a note: Eventually, I will add to this process to create several layers of nested elements, but wanted to get just the first couple layers right before I begin nesting things further as once I do that additional nesting should be relatively easy.
Compare
var children1 = window[parent1].children;
to
var numbchildren2 = window[child1].length;
I think the second one is missing a ".children" before the length. As Shaed, pointed out, numbchildren2 being incorrectly initialized was the most probable cause of the for loop not running, so you should have been investigating that.
I am not familiar with your syntax of window[elementID] to get an element, but I am pretty sure it does not work. Try using document.getElementById instead.
http://jsfiddle.net/M9jtt/

Multiplying Variables Not Alerting

I have a script which calls variable values from input fields and multiplies them,
At the minute my function isnt executing, Im getting no alert neither, I think this is because of my if statement, can anybody see whats going wrong?
function Calculate() {
var ContentMinutes = document.getElementById ("ContentMinutes").value;
var ContentMinutesSelect = document.getElementById('ContentMinutesDD')
.options[document.getElementById('ContentMinutesDD').selectedIndex].value
if (ContentMinutesSelect == 0.0166)
{
var RenderingHours = 10;
var VideoHours = 5;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else if (ContentMinutesSelect == 0.0003)
{
var RenderingHours = 1540;
var VideoHours = 54;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else
{
var RenderingHours = 6410;
var VideoHours = 345;
var VideoSeconds = 124;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
var NoOfFrames = document.getElementById ("NoOfFrames").value;
//var EstimatedCoreHours = document.getElementById ("EstimatedCoreHours").value;
var ServiceLevel = document.getElementById('SerivceLevelDD')
.options[document.getElementById('SerivceLevelDD').selectedIndex].value;
var RenderHours = 1;
var CoresInTest = document.getElementById ("CoresInTest").value;
var EstimatedCoreHours = GetNumeric(NoOfFrames)
* GetNumeric(RenderingHours)
* GetNumeric(CoresInTest);
var EstimatedTotal = GetNumeric(ServiceLevel)
* GetNumeric(EstimatedCoreHours);
alert('Estimated Cost = '
+EstimatedTotal.toFixed(2)
+ 'Estimated Core Hours = '
+EstimatedCoreHours);
document.getElementById("EstimatedCoreHours").innerHTML =
EstimatedCoreHours.toFixed(2);
document.getElementById("EstimatedTotal").innerHTML =
EstimatedTotal.toFixed(2);
document.getElementById("EstimatedCoreHours").style.backgroundColor="yellow";
document.getElementById("EstimatedTotal").style.backgroundColor="yellow";
}
function GetNumeric(val) {
if (isNaN(parseFloat(val))) {
return 0;
}
return parseFloat(val);
}
if (ContentMinutesSelect == 0.0166) i think when you do .value you will get string result.
So your comparision should be
if (ContentMinutesSelect == "0.0166")
Your code will display no alert if any line before it results in an error , like if there isn't an element with the id 'ContentMinutes' in your document . The best way to debug would be to use something like firebug , or you could always put in a bunch of alerts and figure out what goes wrong.

Categories

Resources