I am new to Javascript so this is probably an easy fix but I cannot figure out. I am making a calculator using HTML, CSS and Javascript
and I pretty much only know about declaration, if/else statement, for/while loops and some basic elements of CSS and HTML.
here is my javascript code for the calculator.
var firstNum, operator, previousKey, previousNum;
const calculator = document.querySelector('.calculator');
const buttons = calculator.querySelector('.calculator__buttons');
const display = document.querySelector('.calculator__display');
function calculate(n1, operator, n2) {
let result = '';
if(operator === '+'){
result = n1 + n2;
}else if(operator === '-'){
result = n1 - n2;
}else if(operator === '*'){
result = n1 * n2;
}else if(operator === '/'){
result = n1 / n2;
}
return result;
}
buttons.addEventListener('click', function (event) {
const target = event.target;
const action = target.classList[0];
const buttonContent = target.textContent;
if (target.matches('button')) {
let firstNum = 0;
if (action === 'number') {
if (display.textContent > 0 ) {
display.textContent += buttonContent //
}
else {display.textContent = buttonContent}
//display.textContent = buttonContent
console.log('number1 ' + buttonContent + ' button1');
previousKey = 'number';
}
if (action === 'operator') {
console.log('operator1 ' + buttonContent + ' button1');
operator = buttonContent;
firstNum = display.textContent
//console.log(firstNum)
return firstNum
previousKey = 'operator';
}
if (action === 'decimal') {
// console.log('deciaml1');
previousKey = 'decimal';
}
if (action === 'clear') {
display.textContent = '0'
console.log('clear1');
previousKey = 'clear';
}
if (action === 'calculate') {
console.log('caculate1');
display.textContent = calculate(firstNum, operator, display.textContent)
previousKey = 'calculate';
}
}
});
although I set arithmetic operations above as function calculate(n1, operator, n2)
my caculator // here is what it looks like.
result of 5-9 comes out as -59.
I will appreciate if I could get some help.
thank you in advance.
The issue is that you are sending in strings to the calculate function. So you should explicitly convert the string textContent to integer values as such in your code:
if (action === 'calculate') {
console.log('caculate1');
display.textContent = calculate(parseInt(firstNum,10), operator, parseInt(display.textContent,10))
previousKey = 'calculate';
}
I'm trying to get the quiz to loop 5 times while recording the correct answer for each question before returning to start menu but I'm struggling to get it working
Any help with this will be much appreciated.
function cleartxt()
{
setTimeout("document.getElementById('ans').innerHTML = ''", 3000);
}
var random = new Array(5);
var count = 0;
function next()
{
var store = 0;
do
{
store = (Math.round(Math.ceil(Math.random() * 40) -1));
}while(random.indexOf(store) > -1);
document.getElementById("ques").innerHTML = questions[store][0];
document.getElementById("rad1").innerHTML = questions[store][1];
document.getElementById("rad2").innerHTML = questions[store][2];
document.getElementById("rad3").innerHTML = questions[store][3];
document.getElementById("rad4").innerHTML = questions[store][4];
document.getElementById("image").src = images[store];
var radio = document.getElementsByName("rad");
while(store <= 5)
{
count++;
if(store == 5)
startMenu();
if(radio[0].checked == true)
{
if(questions[store][0] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[1].checked == true)
{
if(questions[store][1] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[2].checked == true)
{
if(questions[store][2] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[3].checked == true)
{
if(questions[store][3] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else
document.getElementById("ans").innerHTML = "Please select an answer!";
}
}
function startMenu()
{
window.history.back();
}
I need to have 2 javascript file running on one single HTML file.
<script type="text/javascript" src="scripts/enhancements.js"></script>
<script type="text/javascript" src="scripts/part2-payment.js"></script>
Both of these script will be loaded in my payment.html page
But it is conflicting because it is loading the bottom one rather than the top one.
Script 1 - part2-payment.js
/**
* Author: Kelvin Chong Choon Siong
* Target: payment.html
* Purpose: Validate and carry forward information to Payment.html
* Created: 14 Apr 2017
* Last updated: 17-04-17
*/
"use strict";
function destroyAll(){
sessionStorage.clear();
window.location = "index.html";
}
function calcCost(bikeType, quantity){
var result = "";
if (bikeType == "Road Bicycle (City Bike) $300") {
result = (300) * quantity;
}
if (bikeType == "Cyclocross Bicycle $330") {
result = (330) * quantity;
}
if (bikeType == "Touring Bicycle $310") {
result = (310) * quantity;
}
if (bikeType == "Track/Fixed-Gear Bicycle $380") {
result = (380) * quantity;
}
if (bikeType == "Mountain Bicycle $340") {
result = (340) * quantity;
}
if (bikeType == "BMX Bicycle $380") {
result = (380) * quantity;
}
if (bikeType == "Folding Bicycle $450") {
result = (450) * quantity;
}
if (bikeType == "Tandem Bicycle $600") {
result = (600) * quantity;
}
return result;
}
function getBooking(){
if(sessionStorage.fname != undefined){ //if sessionStorage for username is not empty
//confirmation text
document.getElementById("fname").textContent = sessionStorage.fname + " " + sessionStorage.lname;
document.getElementById('address').textContent = sessionStorage.address + ", " + sessionStorage.suburb + ", " + sessionStorage.state + ", " + sessionStorage.postcode;
document.getElementById('emailadd').textContent = sessionStorage.emailadd;
document.getElementById('phonenumber').textContent = sessionStorage.pnumber;
document.getElementById('features').textContent = sessionStorage.extra;
document.getElementById('comments').textContent = sessionStorage.comments;
document.getElementById('type_bike').textContent = sessionStorage.bikeType;
document.getElementById('quantity1').textContent = sessionStorage.quantity;
document.getElementById('sizez').textContent = sessionStorage.size;
document.getElementById('cost').textContent = ("AU$ " + calcCost(sessionStorage.bikeType, sessionStorage.quantity));
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.fname;
document.getElementById("lastname").value = sessionStorage.lname;
document.getElementById("emailAddress").value = sessionStorage.emailadd;
document.getElementById("homeAddress").value = sessionStorage.address;
document.getElementById("suburbs").value = sessionStorage.suburb;
document.getElementById("states").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("radioButtons").value = sessionStorage.radiobutton;
document.getElementById("pnumber").value = sessionStorage.pnumber;
document.getElementById("type_bike[]").value = sessionStorage.bikeType;
document.getElementById("quantity[]").value = sessionStorage.quantity;
document.getElementById("size[]").value = sessionStorage.size;
document.getElementById("costFinal").value = calcCost(sessionStorage.bikeType, sessionStorage.quantity)
document.getElementById("extraFeature").value = sessionStorage.extra;
document.getElementById("comment").value = sessionStorage.comments;
}
}
function cardExpiry(){
var errMsg = "";
var getExpiryDate = document.getElementById("expirydate").value;
var getMonth = String(getExpiryDate).charAt(0) + String(getExpiryDate).charAt(1);
var getYear = String(getExpiryDate).charAt(3) + String(getExpiryDate).charAt(4);
var dateNow = new Date ();
var expiryInput = new Date();
expiryInput.setFullYear('20' + getYear, getMonth-1, 1);
if (expiryInput < dateNow){
errMsg = "Your expiration date is before current date. Please change it.\n"
}
return errMsg;
}
function cardValidation() {
/*Visa cards have 16 digits and start with a 4
MasterCard have 16 digits and start with digits 51 through to 55
American Express has 15 digits and starts with 34 or 37.*/
var errMsg = "";
var cardNumber = document.getElementById('cardnum').value;
var cardType = document.getElementById('cardType').value;
var number0 = String(cardNumber).charAt(0);
var number1 = String(cardNumber).charAt(1);
switch (cardType) {
case "Visa":
if ((number0 !== "4") || (cardNumber.length !== 16)) {
errMsg = "Visa cards have 16 digits and start with a 4.\n";
}
break;
case "Mastercard":
if (((number0) !== "5") || ((number1) !== "1" && ((number1) !== "2") && ((number1) !== "3") && ((number1) !== "4") && ((number1) !== "5") ) || (cardNumber.length !== 16)) {
errMsg = "MasterCard have 16 digits and start with digits 51 through to 55.\n";
}
break;
case "Amex":
if (((number0) !== "3") || ((number1) !== "4" && ((number1) !== "7")) || (cardNumber.length !== 15)) {
errMsg = "Amex cards have 15 digits and start with a 34 or 37.\n";
}
break;
default:
errMsg = "Please write your correct card number.\n";
}
return errMsg;
}
function cvvValidation(){
var errMsg = "";
var cardType = document.getElementById('cardType').value;
var cvvcheck = document.getElementById('CVV').value;
//3 digits, for Visa and Mastercard, 4 digits for American Express.
switch (cardType) {
case "Visa":
if (cvvcheck.length !== 3) {
errMsg = "Visa cards have a CVV of 3 digits.\n";
}
break;
case "Mastercard":
if (cvvcheck.length !== 3) {
errMsg = "MasterCards have a CVV of 3 digits.\n";
}
break;
case "Amex":
if (cvvcheck.length !== 4) {
errMsg = "Amex cards have a CVV of 4 digits..\n";
}
break;
default:
errMsg = "Please write your correct card CVV.\n";
}
return errMsg;
}
function validate() {
var errMsg = "";
var result = true;
var checkCard = cardValidation();
if (checkCard !== "") {
errMsg = errMsg + checkCard;
result = false ;
}
var checkCVV = cvvValidation();
if (checkCVV !== "") {
errMsg = errMsg + checkCVV;
result = false ;
}
var checkExpiry = cardExpiry();
if (checkExpiry !== ""){
errMsg = errMsg + checkExpiry;
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result;
}
function init() {
getBooking();
var regForm = document.getElementById("form2");
regForm.onsubmit= validate;
var destroyEverything = document.getElementById('cancelout');
destroyEverything.onclick = destroyAll;
}
window.onload = init;
So this is Script 2 now
Script 2 - enhancements.js
"use strict";
function writeNewMessage(){
var sMessage = document.getElementById('spanny');
sMessage.textContent = "this is a test";
}
function init2() {
var labelTest = document.getElementById("booking_form");
labelTest.onclick = writeNewMessage;
}
window.onload = init2;
I can't figure out how to load both in at the same time.
A few restrictions that I have (because most of the solutions provided on the net I can't use)
body onload
No Inline javascript
No jQuery
So I was wondering if there is another one to make both work?
Your onloads are overwriting each other:
window.onload = init2;//will override window.onload=init;
So do:
window.addEventListener("load",init2);
Same for all the other clicks, etc.
Managed to figure it out by using
window.onload = function() {
init();
init2();
};
doing this on either one of the js script would work.
All good. On n'est jamais mieux servi que par soi-meme.
We get PDF's with the following formatted data.
14424, 14(100-103,706), 1488(zip 5-6,3),14(100-103,706,715,402-408,112),ect...
I need to take that data and parse it out to generate the given zip codes
14424,14100,14101,14102,14103,14706,14885,14886,14883
$('form').submit(function(e) {
$('textarea').val(parse_zip($('textarea').val()));
e.preventDefault();
});
function parse_zip(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
final_result = formated;
} else {
final_result = formated;
valid = false;
}
if (valid) {
return final_result;
} else {
return final_result + ' = Invalid';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha256-7s5uDGW3AHqw6xtJmNNtr+OBRJUlgkNJEo78P4b0yRw= sha512-nNo+yCHEyn0smMxSswnf/OnX6/KwJuZTlNZBjauKhTK0c+zT+q5JOCx0UFhXQ6rJR9jg6Es8gPuD2uZcYDLqSw=="
crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha256-KXn5puMvxCw+dAYznun+drMdG1IFl3agK0p/pqT9KAo= sha512-2e8qq0ETcfWRI4HJBzQiA3UoyFk6tbNyG+qSaIBZLyW9Xf3sWZHN/lxe9fTh1U45DpPf07yj94KsUHHWe4Yk1A==" crossorigin="anonymous"></script>
<form>
<textarea class='form-control input-sm' rows="10">Before: 14424, 14(100-103,706), 1488(zip 5-6,3)</textarea>
<button type='submit'>
submit
</button>
</form>
<p class="help-block">
<br>Before: 14424, 14(100-103,706), 1488(zip 5-6,3)
<br>After: 14424,14100,14101,14102,14103,14706,14885,14886,14883
</p>
How can I parse this out?
EDIT
I have started on the parsing project, but I have come to a few stumbling blocks. here is what I have so far.
function rangeParser(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
var newString = '';
var openLeft = false;
for (var i = 0, len = formated.length; i < len; i++) {
if (formated[i] === '(') {
if (openLeft) {
/*if two left parentheses are open, then it's invalid*/
valid = false;
break;
} else {
openLeft = true;
}
} else if (formated[i] === ')') {
if (openLeft) {
openLeft = false;
} else {
/*if no left parentheses are open and you close it with a right parenthese, the it's invalid*/
valid = false;
break;
}
} else if (formated[i] === ',') {
if (openLeft) {
/*if you are between parentheses then use the '|' as a deliminator to be split latter*/
newString += '|';
} else {
newString += ',';
}
} else {
newString += formated[i];
}
}
if (valid) {
/*splits the string into seperate equations*/
var newArray = newString.split(',');
var append = '';
var substr = [];
var smsplit = [];
var addtome = [];
var addnext = '';
for (var i = 0, len = newArray.length; i < len; i++) {
if (/[^\d]/g.test(newArray[i])) {
if (/^\d/.test(newArray[i])) {
/*graps the appending digits*/
append = /^\d+/.exec(newArray[i])[0];
/*gets the string that will be parsed for generating automation*/
substr = newArray[i].substring(append.length).replace(/[^\d\-|,]+/g, '').split('|');
for (var j = 0, l = substr.length; j < l; j++) {
smsplit = substr[j].split('-');
if (smsplit.length === 2 && parseInt(smsplit[0]) < parseInt(smsplit[1])) {
if (parseInt(smsplit[0]) < parseInt(smsplit[1])) {
for (var k = parseInt(smsplit[0]), leng = parseInt(smsplit[1]); k < leng; k++) {
addnext = append + '' + k;
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
break;
}
}
} else {
/*if the ints are backwards, invalid*/
valid = false;
break;
}
} else if (smsplit.length === 1) {
addnext = append + '' + smsplit[0];
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
break;
}
} else {
/*if there are more than one dash, invalid*/
valid = false;
break;
}
if (!valid) {
break;
}
}
if (!valid) {
break;
}
} else {
/*if the string does not start with a digit, invalid*/
valid = false;
break;
}
} else if (newArray[i].length === 5) {
/*if it is a 5 digit number continue*/
addtome.push(newArray[i]);
continue;
} else {
/*if it has less or more than 5 digits and no special characters then it's invalid*/
valid = false;
break;
}
}
if (valid) {
final_result = uniq_fast(addtome).join(',');
}
}
} else {
valid = false;
}
if (valid) {
return final_result;
} else {
return formated + ' = Invalid';
}
}
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for (var i = 0; i < len; i++) {
var item = a[i];
if (seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out.sort();
}
This is a rudimentary answer and I would love to see if someone can come up with a better answer than mine, that out preforms it.
$('#sub').click(function() {
$('textarea').val(rangeParser($('textarea').val()));
});
$('#re').click(function() {
$('textarea').val('Before: 14424, 14(100-103,706), 1488(zip 5-6,3)');
});
function rangeParser(zip_codes) {
var valid = true;
var formated = zip_codes.replace(/[^\d()\-,]+/g, '');
var final_result = '';
var invalidtext = '';
/*if begins with digit*/
if (/^\d/.test(formated)) {
var newString = '';
var openLeft = false;
for (var i = 0, len = formated.length; i < len; i++) {
if (formated[i] === '(') {
if (openLeft) {
/*if two left parentheses are open, then it's invalid*/
valid = false;
invalidtext = 'two left';
break;
} else {
openLeft = true;
newString += formated[i];
}
} else if (formated[i] === ')') {
if (openLeft) {
openLeft = false;
newString += formated[i];
} else {
/*if no left parentheses are open and you close it with a right parenthese, the it's invalid*/
valid = false;
invalidtext = 'no left';
break;
}
} else if (formated[i] === ',') {
if (openLeft) {
/*if you are between parentheses then use the '|' as a deliminator to be split latter*/
newString += '|';
} else {
newString += ',';
}
} else {
newString += formated[i];
}
}
if (valid) {
/*splits the string into seperate equations*/
var newArray = newString.split(',');
var append = '';
var substr = [];
var smsplit = [];
var addtome = [];
var addnext = '';
for (var i = 0, len = newArray.length; i < len; i++) {
if (/[^\d]/g.test(newArray[i])) {
if (/^\d/.test(newArray[i])) {
/*graps the appending digits*/
append = /^\d+/.exec(newArray[i])[0];
/*gets the string that will be parsed for generating automation*/
substr = newArray[i].substring(append.length).replace(/[^\d\-|,]+/g, '').split('|');
for (var j = 0, l = substr.length; j < l; j++) {
smsplit = substr[j].split('-');
if (smsplit.length === 2 && parseInt(smsplit[0]) < parseInt(smsplit[1])) {
if (parseInt(smsplit[0]) < parseInt(smsplit[1])) {
for (var k = parseInt(smsplit[0]), leng = parseInt(smsplit[1]); k <= leng; k++) {
addnext = append + '' + k;
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
invalidtext = 'ranged non five digit';
break;
}
}
} else {
/*if the ints are backwards, invalid*/
valid = false;
invalidtext = 'backwards range';
break;
}
} else if (smsplit.length === 1) {
addnext = append + '' + smsplit[0];
if (addnext.length === 5) {
addtome.push(addnext);
} else {
/*if zip is not 5 digits long, invalid*/
valid = false;
invalidtext = 'not five digit zip range';
break;
}
} else if (smsplit.length > 2) {
/*if there are more than one dash, invalid*/
valid = false;
invalidtext = 'more than one dash';
break;
}
if (!valid) {
break;
}
}
if (!valid) {
break;
}
} else {
/*if the string does not start with a digit, invalid*/
valid = false;
invalidtext = 'donst start with digit';
break;
}
} else if (newArray[i].length === 5) {
/*if it is a 5 digit number continue*/
addtome.push(newArray[i]);
continue;
} else {
/*if it has less or more than 5 digits and no special characters then it's invalid*/
valid = false;
invalidtext = 'non range not five digit';
break;
}
}
if (valid) {
final_result = uniq_fast(addtome).join(',');
}
}
} else {
/*if starting string doesn't have digit at first*/
invalidtext = 'begin non digit';
valid = false;
}
if (valid) {
return final_result;
} else {
return formated + ' = Invalid ' + invalidtext;
}
}
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for (var i = 0; i < len; i++) {
var item = a[i];
if (seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out.sort();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<textarea class='form-control input-sm' rows="10">Before: 14424, 14(100-103,706), 1488(zip 5-6,3)</textarea>
<button id="sub">
submit
</button>
<button id="re">
Reset
</button>
<p class="help-block">
<br>Before: 14424, 14(100-103,706), 1488(zip 5-6,3)
<br>After: 14100,14101,14102,14103,14424,14706,14883,14885,14886
</p>
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"));