I don't know what's wrong with my code, but when I use addEventListener() it doesn't do a thing.
Does anyone have another solution so that I can bind the #ibm button ID to compute() onClick event?
I plan to run this on Firfox OS, so setting an onClick attribute on the button itself is prohibited as stated on the CSP Violations.
function compute()
{
var w = parseInt(document.getElementById('weight').value);
var hf = parseInt(document.getElementById('height_ft').value);
var hi = parseInt(document.getElementById('height_in').value);
if (!checker(w))
{
showAndroidToast('Please input your weight');
return;
}
else if (!checker(hf))
{
showAndroidToast('Please input your height');
return;
}
if (!checker(hi))
{
var i = 0;
document.getElementById('height_in').value = i;
}
else
{
var i = parseInt(document.getElementById('height_in').value);
}
var comp_h = parseFloat((hf * 12) + (i * 1));
var tot_h = comp_h * comp_h;
comp = formula(w, tot_h);
document.getElementById('bmitot').value = comp;
if (comp > 30)
{
document.getElementById('res').value = 'Severe Level! Thats too much FAT! Go get some diet pills or something!';
document.getElementById("bmitot").style.backgroundColor = "red";
document.getElementById("zero").style.visibility = "hidden";
document.getElementById("one").style.visibility = "hidden";
document.getElementById("two").style.visibility = "hidden";
document.getElementById("three").style.visibility = "visible";
}
if (comp > 25 && comp <=29.9)
{
document.getElementById('res').value = 'Bad Level! You are too FAT!';
document.getElementById("bmitot").style.backgroundColor = "yellow";
document.getElementById("zero").style.visibility = "hidden";
document.getElementById("one").style.visibility = "hidden";
document.getElementById("two").style.visibility = "visible";
document.getElementById("three").style.visibility = "hidden";
}
if (comp > 18.5 && comp <=24.9)
{
document.getElementById('res').value = 'Nice! You are on the safe level!';
document.getElementById("bmitot").style.backgroundColor = "green";
document.getElementById("zero").style.visibility = "hidden";
document.getElementById("one").style.visibility = "visible";
document.getElementById("two").style.visibility = "hidden";
document.getElementById("three").style.visibility = "hidden";
}
if (comp < 18.5)
{
document.getElementById('res').value = 'Bad Level! Go get some nutrients!';
document.getElementById("bmitot").style.backgroundColor = "yellow";
document.getElementById("zero").style.visibility = "visible";
document.getElementById("one").style.visibility = "hidden";
document.getElementById("two").style.visibility = "hidden";
document.getElementById("three").style.visibility = "hidden";
}
}
function formula(w, h)
{
var bmi = w/h * 703;
var a_bmi = Math.floor(bmi);
var dif = bmi - a_bmi;
dif = dif * 10;
diff = Math.round(dif);
if (dif == 10)
{
a_bmi += 1;
dif = 0;
}
bmi = a_bmi + "." + diff;
return bmi;
}
function checker(type)
{
if (isNaN(parseInt(type)))
{
return false;
}
else if (type < 0)
{
return false;
}
else
{
return true;
}
}
function showAndroidToast(toast)
{
Android.showToast(toast);
}
document.getElementById('ibm').addEventListener('click', compute);
Your code is executing fine and compute function is triggering fine. There may be an issue with the code in execute function. Check this fiddle
Related
I've made a meteor "game". On window load I set my shield:
window.onload = function() {
document.getElementById("shield").innerHTML = "Max";
var playStart = document.getElementById("playBtn");
playStart.addEventListener("click", playGame);
}
On a click of the play button I'm calling a function (playGame) to loop (currently 20 odd times). In this loop I call my meteor create function (called setUp):
function playGame() {
for (i = 0; i < 21; i++) {
if (document.getElementById("shield").innerHTML != "End") {
setUp();
} else {
continue;
}
}
}
In setup I create the meteor and animate it. I've added an event listener so that on the animation's end (i.e. the "player" hasn't destroyed the meteor) it calls a function to remove the meteor and change the shield status:
function setup() {
imgMeteor.addEventListener("animationend", imgEnd);
// This function (imgEnd is within my setUp function).
function imgEnd() {
var child = document.getElementById("imgMeteor");
imgMeteor.parentNode.removeChild(imgMeteor);
var currShield = document.getElementById("shield").innerHTML;
switch (currShield) {
case "Max":
currShield = "Med";
break;
case "Med":
currShield = "Min";
break;
case "Min":
currShield = "None";
break;
case "None":
currShield = "End";
break;
}
document.getElementById("shield").innerHTML = currShield;
if (currShield == "End") {
return;
}
}
}
(I've tried to show just the relevant code). How can I stop the loop running. (Basically I want the game to end once the barrier is "End"?
Any help would be awesome. Entire code below if that helps.
var numText = ["Zero", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine"
];
var modText = ["0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9"];
window.onload = function() {
document.getElementById("shield").innerHTML = "Max";
var arrNum = 0;
document.getElementById("spdText").innerHTML = numText[arrNum];
myNum = arrNum;
var upSpd = document.getElementById("upBtn");
upSpd.addEventListener("click", nextyNum);
var downSpd = document.getElementById("downBtn");
downSpd.addEventListener("click", prevyNum);
var playStart = document.getElementById("playBtn");
playStart.addEventListener("click", playGame);
var playPause = document.getElementById("pauseBtn");
playPause.addEventListener("click", pauseGame);
}
function nextyNum() {
myNum += 1;
if (myNum <= 9) {
document.getElementById("spdText").innerHTML = numText[myNum];
document.getElementById("warpProg").value = [myNum];
document.getElementById("currMod").innerHTML = modText[myNum]
} else {
alert("She cannie take any more cap'n. Speed's at maximum");
}
if (myNum > 9) {
myNum = 9;
}
progColourCheck();
}
function prevyNum() {
myNum -= 1;
if (myNum >= 0) {
document.getElementById("spdText").innerHTML = numText[myNum];
document.getElementById("warpProg").value = [myNum];
document.getElementById("currMod").innerHTML = modText[myNum];
} else {
alert("She's as low as she can go cap'n ");
}
if (myNum < 0) {
myNum = 0;
}
progColourCheck();
}
function progColourCheck() {
var progColours = ["lightgrey", "lightyellow", "yellow", "greenyellow", "lawngreen", "#73e600",
"#cc9900", "orange", "orangered", "red"
];
document.getElementById("warpProg").style.color = progColours[myNum];
document.getElementById("currMod").style.backgroundColor = progColours[myNum];
}
function playGame() {
var tempScore = document.getElementById(currScore);
tempScore = parseInt(currScore.innerHTML);
var hiScore = document.getElementById(hScore);
hiScore = parseInt(hScore.innerHTML);
if (tempScore > hiScore) {
hScore.innerHTML = tempScore;
}
currScore.innerHTML = 0000;
if (myNum == 0) {
alert("The ship's not movin' cap'n");
return;
}
for (i = 0; i < 21; i++) {
if (document.getElementById("shield").innerHTML != "End") {
document.getElementById("upBtn").disabled = "true";
document.getElementById("downBtn").disabled = "true";
setUp();
} else {
continue;
}
}
document.getElementById("titleText").style.visibility = "hidden";
document.getElementById("playBtn").style.visibility = "hidden";
}
function setUp() {
var imgMeteor = document.createElement("p");
var blankNode = document.createTextNode("");
imgMeteor.appendChild(blankNode);
document.getElementById("canvas").appendChild(imgMeteor);
imgMeteor.style.visibility = "hidden";
imgMeteor.style.backgroundImage = 'url("meteor.gif")';
imgMeteor.style.width = "56px";
imgMeteor.style.height = "56px";
imgMeteor.style.position = "absolute";
imgMeteor.addEventListener("mouseover", removeElement);
imgMeteor.style.animationName = "animBlock";
imgMeteor.style.animationDuration = 10 - myNum + "s";
imgMeteor.style.animationDelay = Math.floor(Math.random() * (8 - 0 + 1)) + 0 + "s";
imgMeteor.style.animationTimingFunction = "linear";
imgMeteor.addEventListener("animationstart", imgVis);
function imgVis() {
imgMeteor.style.visibility = "visible";
}
imgMeteor.addEventListener("animationend", imgEnd);
var leftPos = xPosition(0);
imgMeteor.style.left = leftPos + "%";
var topPos = yPosition(0);
imgMeteor.style.top = topPos + "px";
function removeElement() {
var cScore = document.getElementById("CurrScore");
cScore = parseInt(currScore.innerHTML);
cScore += (1 * myNum);
currScore.innerHTML = cScore;
var child = document.getElementById("imgMeteor");
imgMeteor.parentNode.removeChild(imgMeteor);
document.getElementById("barrier").style.background = "linear-gradient(darkblue, lightblue)";
}
function imgEnd() {
var child = document.getElementById("imgMeteor");
imgMeteor.parentNode.removeChild(imgMeteor);
document.getElementById("barrier").style.background = "linear-gradient(red, orange)";
var cScore = document.getElementById("CurrScore");
cScore = parseInt(currScore.innerHTML);
var negScore = myNum;
if (negScore > 1) {
negScore -= 1;
}
cScore -= (1 * negScore);
currScore.innerHTML = cScore;
var currShield = document.getElementById("shield").innerHTML;
switch (currShield) {
case "Max":
currShield = "Med";
break;
case "Med":
currShield = "Min";
break;
case "Min":
currShield = "None";
document.getElementById("bubble").style.visibility = "hidden";
break;
case "None":
currShield = "End";
break;
}
document.getElementById("shield").innerHTML = currShield;
if (currShield == "End") {
return;
}
}
}
function xPosition(lPos) {
var lPos = Math.floor(Math.random() * (90 - 1 + 1)) + 1;
return lPos;
}
function yPosition(tPos) {
var tPos = Math.floor(Math.random() * (80 - 10 + 1)) + 10;
return tPos;
}
function pauseGame() {
playBtn.style.visibility = "visible";
document.getElementById("upBtn").disabled = "false";
document.getElementById("downBtn").disabled = "false";
document.getElementById("shield").innerHTML = "Max";
}
Your loop should look like this then:
function playGame() {
for (i=0; i < 21; i++) {
if (document.getElementById("shield").innerHTML == "End"){
break;
}
SetUp();
}
}
You want to break the loop when the condition is met.
Currently, I am using an archaic method of setting a variable true at the start of the animation and false after the animation has played (see below.) I also think something might be wrong with how I process animations in the interval because when I add an animation to the array of animations to be processed, it isn't processed. Here's my code:
var animationDone = true;
function g_e(e){
return document.getElementById(e);
};
class Main{
constructor(){
this.animations = [];
this.tasks = [];
}
start_animating(){
var x = setInterval(function (){
if (animationDone == true){
try{
alert(this.animations[0]);
this.aminations[0].func(this.animations[0].args);
this.animations.shift();
}
catch(e){
}
}
},1);
}
add_animation(f, a){
this.animations.push({func:f, args:a});
alert("animation added");
}
start_working(){
var x = setInterval(function (){
try{
this.tasks[0].func(this.tasks[0].args);
this.tasks.shift();
}
catch(e){
}
},1);
}
animation_blink(){
var blink = 0;
window.setInterval(function blinking(){
if (blink == 0){
document.getElementById("blinker").innerHTML = ">";
blink= 1;
}
else if(blink == 1){
document.getElementById("blinker").innerHTML=" ";
blink = 0;
}
}, 1000);
}
animation_fade(object){
var fade = 0;
var fadeOut = 0;
animationDone = false;
var interval = setInterval(function startFade(){
g_e(object.element).style.opacity = fade;
if(fade>1 && fadeOut == 0){
fadeOut = 1;
}
else if(fade < 0){
clearInterval(interval);
}
else if(fadeOut == 0){
fade = fade + 0.2;
}
else if(fadeOut == 1){
fade = fade - 0.2;
}
}, 500);
animationDone = true;
}
plbl(object){
animationDone = false;
var p = plbl.intervals;
if (!p)
plbl.intervals = p = {};
if (p[object.destination])
clear();
function clear() {
clearInterval(p[object.destination]);
delete p[object.destination];
}
var i = 0;
var elem = document.getElementById(object.destination);
p[object.destination] = setInterval(function(){
checkChar = object.message.charAt(i);
if(checkChar =="|"){
elem.innerHTML += "<br>";
}
else{
elem.innerHTML += object.message.charAt(i);
}
i++;
if (i > message.length){
animationDone = true;
clear();
}
}, object.speed);
}
command(input){
alert(input);
if(input == "y"){
g_e("start").style.display = "none";
g_e("startUp").style.display = "block";
this.add_animation("test", "test");
}
}
get_input(){
var x = g_e("input").value;
g_e("input").value = "";
return x;
}
key_checker(event){
var key = event.keyCode;
if (key == 13){
this.command(this.get_input());
return false;
}
}
start(){
this.start_working();
this.start_animating();
this.animation_blink();
}
}
alert("compiled");
main = new Main();
main.start();
I'm facing an issue with Java Script.
I have a piece of code that creates rain inside a div and I need this rain to turn off and on according to my if statements.
Here is that JS code that makes rain work.
var nbDrop = 120;
// function to generate a random number range.
function randRange( minNum, maxNum) {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
// function to generate drops
function createRain() {
for( i=1;i<nbDrop;i++) {
var dropLeft = randRange(0,1280);
var dropTop = randRange(-500,590);
$('.rain').append('<div class="drop" id="drop'+i+'"></div>');
$('#drop'+i).css('left',dropLeft);
$('#drop'+i).css('top',dropTop);
}
}
createRain();
So further I have a series of if statements and I want to change nbDrop variable which controls a number of drops. I want only one condition to result in raining, while others should set it to 0 value.
function displayAnswer(answer) {
var fortuneText = document.getElementById('answer');
if (chosenAnswer == 0){
nbDrop = 0;
}
else if (chosenAnswer == 1){
nbDrop = 0;
}
else if (chosenAnswer == 2){
nbDrop = 0;
}
else if (chosenAnswer == 3){
nbDrop = 0;
}
else if (chosenAnswer == 4){
nbDrop = 0;
}
else if (chosenAnswer == 5){
var nbDrop = 120;
// function to generate a random number range.
function randRange( minNum, maxNum) {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
// function to generate drops
function createRain() {
for( i=1;i<nbDrop;i++) {
var dropLeft = randRange(0,1280);
var dropTop = randRange(-500,590);
$('.rain').append('<div class="drop" id="drop'+i+'"></div>');
$('#drop'+i).css('left',dropLeft);
$('#drop'+i).css('top',dropTop);
}
}
createRain();
}
}
A problem is that it only works once when the last if statement is true. But when other conditions are true, rain keeps going, so that variable doesn't change to 0 for some reason. It stays at 120.
Even though the button I use to click to change if statements condition has an even listener on it:
<button id="button1" onclick="displayAnswer();"></button>
Is there any way to make that nbDrop variable change to zero for all other if conditions, except one which should have it set to 120?
1: You should remove the "var" in condition == 5, as it is already declared.
else if (chosenAnswer == 5){
// var nbDrop = 120;
nbDrop = 120;
2: The commented method will not run when the nbDrop is 0 as i start on 1 and 1 can never be smaller than 0
function createRain() {
// for( i=1;i<nbDrop;i++) {
for( i=0;i<=nbDrop;i++) { // need to be like this
3: You have the } sign in a wrong place. Change it like this (see the "added" and "remove" comments in the code) or the "createRain" only gets called when condition == 5 is met. If you indent your code like below you will easier see within which code block things is.
Update Added an exit part in the "createRain" function
function displayAnswer(answer) {
var fortuneText = document.getElementById('answer');
if (chosenAnswer == 0){
nbDrop = 0;
}
else if (chosenAnswer == 1){
nbDrop = 0;
}
else if (chosenAnswer == 2){
nbDrop = 0;
}
else if (chosenAnswer == 3){
nbDrop = 0;
}
else if (chosenAnswer == 4){
nbDrop = 0;
}
else if (chosenAnswer == 5){
nbDrop = 120;
} // added
// function to generate a random number range.
function randRange( minNum, maxNum) {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
// function to generate drops
function createRain() {
if (nbDrop == 0) {
// remove the drop element(s)
$('.rain').children().remove();
// exit the function
return;
}
for( i=0;i<=nbDrop;i++) {
var dropLeft = randRange(0,1280);
var dropTop = randRange(-500,590);
$('.rain').append('<div class="drop" id="drop'+i+'"></div>');
$('#drop'+i).css('left',dropLeft);
$('#drop'+i).css('top',dropTop);
}
}
createRain();
//} removed
}
And, as requested, here is the fully working web page
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Magic 8 Ball</title>
<link rel="stylesheet" type="text/css" href="index.css" />
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
</head>
<body>
<div id="topmask"></div>
<div id="mainframe">
<div id="mainframe2">
<section class="rain"></section>
<div id="rocketdear"></div><div id="smokedear"></div><div id="launchsmokedear"></div>
</div>
<div id="bubble"></div>
<div id="bubbleHugecat"></div><div id="bubbleHugecatrays"></div>
<div class="sign">
<p id="question"></p>
<p id="answer"></p>
</div>
<div id="eight-ball">
<button id="button1" onclick="javascript:shake();"></button>
</div>
</div>
<div id="bottommask"></div>
<script>
var nbDrop;
function shake() {
var answersArrayed = ["Yes. So nothing happens", "No. Enjoy your consequences", "Ok, but that's something different", "My answer won't help you, deal with it!", "Your questions don't matter anymore", "Your questions make it rain again"];
// The question we asked
var question = prompt("Ask you question...");
var questionText = document.getElementById('question');
questionText.innerHTML = question;
// Number of possible answers
var numberOfAnswers = answersArrayed.length;
// Answers the 8 Ball can return
// Answer returned by our 8 Ball
var chosenAnswer = getAnswerNumber(numberOfAnswers);
displayAnswer(chosenAnswer);
// Returns a number based on the number of sides
function getAnswerNumber(answerCount) {
var number = getRandomInt(0, numberOfAnswers);
return number;
}
// Returns a random integer between two numbers
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
// Show our answer in the document
function displayAnswer(answer) {
}
// Access the DOM element we want to to change
var fortuneText = document.getElementById('answer');
if (chosenAnswer == 0) {
document.getElementById("bubble").className = "bubbleStill";
fortuneText.innerHTML = answersArrayed[0];
document.getElementById("smokedear").style.webkitAnimation = 'none';
document.getElementById("launchsmokedear").style.webkitAnimation = 'none';
document.getElementById("rocketdear").style.webkitAnimation = 'none';
document.getElementById("bubble").style.webkitAnimation = 'none';
document.getElementById("bubble").style.opacity = "0";
document.getElementById("bubbleHugecat").style.opacity = "0";
document.getElementById("bubbleHugecatrays").style.opacity = "0";
document.getElementById("mainframe").style.backgroundImage = "url('desert23.svg')";
document.getElementById("smokedear").className = "smokestill";
document.getElementById("launchsmokedear").className = "launchsmokestill";
document.getElementById("rocketdear").className = "rocketstill";
nbDrop = 0;
}
else if (chosenAnswer == 1) {
fortuneText.innerHTML = answersArrayed[1];
document.getElementById("smokedear").style.webkitAnimation = 'none';
document.getElementById("launchsmokedear").style.webkitAnimation = 'none';
document.getElementById("rocketdear").style.webkitAnimation = 'none';
document.getElementById("bubble").className = "bubbleExploading";
document.getElementById("bubble").style.webkitAnimation = '';
document.getElementById("bubble").style.opacity = "1";
document.getElementById("bubbleHugecat").style.opacity = "0";
document.getElementById("bubbleHugecatrays").style.opacity = "0";
document.getElementById("mainframe").style.backgroundImage = "url('desert23.svg')";
document.getElementById("smokedear").className = "smokestill";
document.getElementById("launchsmokedear").className = "launchsmokestill";
document.getElementById("rocketdear").className = "rocketstill";
nbDrop = 0;
}
else if (chosenAnswer == 2) {
fortuneText.innerHTML = answersArrayed[2];
document.getElementById("smokedear").style.webkitAnimation = 'none';
document.getElementById("launchsmokedear").style.webkitAnimation = 'none';
document.getElementById("rocketdear").style.webkitAnimation = 'none';
document.getElementById("bubble").style.webkitAnimation = 'none';
document.getElementById("bubbleHugecatrays").style.opacity = "1";
document.getElementById("bubbleHugecat").style.opacity = "1";
document.getElementById("mainframe").style.backgroundImage = "url('desert23.svg')";
document.getElementById("bubble").className = "bubbleStill";
document.getElementById("bubble").style.opacity = "0";
document.getElementById("smokedear").className = "smokestill";
document.getElementById("launchsmokedear").className = "launchsmokestill";
document.getElementById("rocketdear").className = "rocketstill";
nbDrop = 0;
}
else if (chosenAnswer == 3) {
document.getElementById("smokedear").style.webkitAnimation = 'none';
document.getElementById("launchsmokedear").style.webkitAnimation = 'none';
document.getElementById("rocketdear").style.webkitAnimation = 'none';
document.getElementById("bubble").style.webkitAnimation = 'none';
fortuneText.innerHTML = answersArrayed[3];
document.getElementById("bubbleHugecat").style.opacity = "0";
document.getElementById("bubbleHugecatrays").style.opacity = "0";
document.getElementById("bubble").className = "bubbleStill";
document.getElementById("bubble").style.opacity = "0";
document.getElementById("mainframe").style.backgroundImage = "url('desert_night.svg')";
document.getElementById("smokedear").className = "smokestill";
document.getElementById("launchsmokedear").className = "launchsmokestill";
document.getElementById("rocketdear").className = "rocketstill";
nbDrop = 0;
}
else if (chosenAnswer == 4) {
fortuneText.innerHTML = answersArrayed[4];
document.getElementById("smokedear").style.opacity = "1";
document.getElementById("launchsmokedear").style.opacity = "1";
document.getElementById("rocketdear").style.opacity = "1";
document.getElementById("smokedear").className = "smoke";
document.getElementById("launchsmokedear").className = "launchsmoke";
document.getElementById("rocketdear").className = "rocket";
document.getElementById("smokedear").style.webkitAnimation = '';
document.getElementById("launchsmokedear").style.webkitAnimation = '';
document.getElementById("rocketdear").style.webkitAnimation = '';
document.getElementById("bubble").style.webkitAnimation = 'none';
document.getElementById("mainframe").style.backgroundImage = "url('desert23.svg')";
document.getElementById("bubbleHugecat").style.opacity = "0";
document.getElementById("bubbleHugecatrays").style.opacity = "0";
document.getElementById("bubble").className = "bubbleStill";
document.getElementById("bubble").style.opacity = "0";
nbDrop = 0;
}
else {
fortuneText.innerHTML = answersArrayed[5];
document.getElementById("smokedear").style.webkitAnimation = 'none';
document.getElementById("launchsmokedear").style.webkitAnimation = 'none';
document.getElementById("rocketdear").style.webkitAnimation = 'none';
document.getElementById("bubble").style.webkitAnimation = 'none';
document.getElementById("smokedear").className = "smokestill";
document.getElementById("launchsmokedear").className = "launchsmokestill";
document.getElementById("rocketdear").className = "rocketstill";
document.getElementById("mainframe").style.backgroundImage = "url('desert_rain.svg')";
document.getElementById("bubbleHugecat").style.opacity = "0";
document.getElementById("bubbleHugecatrays").style.opacity = "0";
document.getElementById("bubble").className = "bubbleStill";
document.getElementById("bubble").style.opacity = "0";
nbDrop = 120;
}
// function to generate a random number range.
function randRange(minNum, maxNum) {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
// function to generate drops
function createRain() {
if (nbDrop == 0) {
// remove the drop element(s)
$('.rain').children().remove();
// exit the function
return;
}
for (i = 0; i <= nbDrop; i++) {
var dropLeft = randRange(0, 1280);
var dropTop = randRange(-500, 590);
$('.rain').append('<div class="drop" id="drop' + i + '"></div>');
$('#drop' + i).css('left', dropLeft);
$('#drop' + i).css('top', dropTop);
}
}
createRain();
}
</script>
</body>
</html>
I would like to add a $5.00 charge whenever the txtBwayEDUGift checkbox is selected. The javascript code I currently have is reducing the amount when checkbox is unchecked, but not applying the charge when selected. I can provide additonal code if needed.
Here is my input type from my aspx page:
<input type="checkbox" name="txtBwayEDUGift" id="txtBwayEDUGift" onchange="checkboxAdd(this);" checked="checked" />
Here is my javascript:
{
var divPrevAmt;
if (type == 0)
{
divPrevAmt = document.getElementById("divBwayGiftPrevAmt");
}
else if (type == 1)
{
divPrevAmt = document.getElementById("divBwayEDUGiftPrevPmt");
}
var txtAmt = document.getElementById(obj);
var amt = txtAmt.value;
amt = amt.toString().replace("$","");
amt = amt.replace(",","");
var prevAmt = divPrevAmt.innerHTML;
try
{
amt = amt * 1;
}
catch(err)
{
txtAmt.value = "";
return;
}
if (amt >= 0) //get the previous amount if any
{
if (type == 0)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
else if (type == 1)
{
if (prevAmt.toString().length > 0)
{
prevAmt = prevAmt * 1;
}
else
{
prevAmt = 0;
}
}
//now update the master total
var total = document.getElementById("txtTotal");
var dTotal = total.value.toString().replace("$","");
dTotal = dTotal.replace(",","");
dTotal = dTotal * 1;
var newTotal = dTotal - prevAmt;
newTotal = newTotal + amt;
divPrevAmt.innerHTML = amt.toString();
newTotal = addCommas(newTotal);
amt = addCommas(amt);
txtAmt.value = "$" + amt;
total.value = "$" + newTotal;
}
else
{
txtAmt.value = "";
return;
}
}
function disable()
{
var txtTotal = document.getElementById("txtTotal");
var txt = txtTotal.value;
txtTotal.value = txt;
var BwayGift = document.getElementById("txtBwayGift");
BwayGift.focus();
}
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
var newTotal = x1 + x2;
if (newTotal.toString().indexOf(".") != -1)
{
newTotal = newTotal.substring(0,newTotal.indexOf(".") + 3);
}
return newTotal;
}
function checkChanged()
{
var cb = document.getElementById("cbOperaGala");
if (cb.checked == true)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "url('images/otTableRowSelect.jpg')";
}
else if (cb.checked == false)
{
var tableRow = document.getElementById("trCheckbox");
tableRow.style.backgroundImage = "";
}
}
function alertIf()
{
var i = 0;
for (i=5;i<=10;i++)
{
try{
var subtotal2 = document.getElementById("txtSubTotal" + i);
var dSubtotal2 = subtotal2.value;
dSubtotal2 = dSubtotal2.replace("$","");
dSubtotal2 = dSubtotal2 * 1;}
catch (Error){dSubtotal2 = 0}
if (dSubtotal2 > 0)
{
alert("You have selected the I want it all package, \n however you have also selected individual tickets to the same events. \n If you meant to do this, please disregard this message.");
break;
}
}
}
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
//Add $5.00 donation to cart
function checkboxAdd(ctl) {
if (ctl.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal( 5, "S");
}
}
</script>
I do not understand the context of the scenario. When a user clicks the checkbox are you making an HTTP request to the server? Or is this a simple form POST page? What is calculateTotal() doing?
I figured it out. So the functionality I had in place was fine.
//Add $5.00 donation to cart
function checkboxAdd(txtBwayEDUGift) {
if (txtBwayEDUGift.checked == true) {
// alert("adding $5");
calculateTotal(5, "A");
} else {
// alert("deducting $5");
calculateTotal(5, "S");
}
}
But I needed to add a load function:
function load() {
calculateTotal(5, "A");
}
<body onload="load()">
Along with adding a reference to my c# page:
if (txtBwayEDUGift.Checked)
{
addDonations(5.00, 93);
}
You can use jQuery :)
$(txtBwayEDUGift).change(calculateTotal(5, "S"));
(second.innerHTML) -1 that worked but (num.innerHTML) -1 that not working why?
function doDcrements() {
var hidden = document.getElementById('hidden');
var second = document.getElementById('second'); // the second is 20.
var loopTimer = 0;
if (second.innerHTML != "0") {
second.innerHTML = (second.innerHTML) -1;
second.style.color = "blue";
loopTimer = setTimeout('doDecrements()',1000);
}else {
second.style.color = "grey";
hidden.style.display = "block";
}
}
.....................................................................................................................................................................
function doDcrements() {
var hidden = document.getElementById('hidden');
var second = document.getElementById('second'); // the second is 20.
var loopTimer = 0;
var num = document.getElementById('num'); // the number is 20.
if (second.innerHTML != "0") {
second.innerHTML = (num.innerHTML) -1;
second.style.color = "blue";
loopTimer = setTimeout('doDecrements()',1000);
}else {
second.style.color = "grey";
hidden.style.display = "block";
}
}
when I create it by for loop it not happens :
function doDcrements() {
var hidden = document.getElementById('hidden');
var second = document.getElementById('second');
for (i=20; i<=0; i--) {
if (second.innerHTML != "0") {
second.innerHTML = i;
second.style.color = "blue";
loopTimer = setTimeout('doDecrements()',1000);
}else {
second.style.color = "grey";
hidden.style.display = "block";
}
}
}
html code:
<div id="hidden">started</div>
<p id="second">20</p>
<div onClick="doDcrements();">Download</div>
Please look at your for loop:
for (i=20; i<=0; i--)
i=20 and i<=0. It will never run.
(second.innerHTML) -1 that worked but (num.innerHTML) -1 that not working why?
Without seeing your code, the only guess is that num.innerHTML is not giving you a string that is convertible to number. Examples:
'20' - 1 = 20
'<input name="xyz" val="20"/>' - 1 = NaN
Your HTML does't have any element with id="num". If this is the case, num will be null.
Changes
setTimeout(doDecrements,1000);
for (i=20; i >=0; i--)