Adding price to total when checkbox is selected - javascript

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"));

Related

Converting unary string of units to binary string only works once (Javascript)

I built an integer conversation from unary string of units = '1' to a binary representation in string format!
The function only works once and is limited to the number 31
here is my approach in javascript - can you help or explain?
func_unary_to_digit = function(p_reg1) {
var grouper = {
group:''
};
var unit = '1';
var p_sys = 2;
var i_grp = 0;
var t1_reg = p_reg1;
var lw1_unary = '';
var rw1_unary = '';
var lw2_unary = '0';
var rw2_unary = '';
for(it_g = 0; it_g < p_sys; it_g++) {
grouper.group += unit;
}
if(p_reg1.length === 1) {
lw1_unary = '';
rw1_unary = unit;
} else {
for (it_s = 0; it_s <= t1_reg.length; it_s++) {
lw1_unary = '';
i_grp = 0;
for (it_c = 0; it_c < t1_reg.length; it_c++) {
if (it_c % grouper.group.length === 1) {
lw1_unary += unit;
i_grp++;
}
}
if (t1_reg.length % grouper.group.length === 0) {
//rw1_unary += inf;
rw1_unary += '0';
}
if (t1_reg.length % grouper.group.length === 1) {
rw1_unary += unit;
}
if (lw1_unary.length === 1) {
lw1_unary = '';
rw1_unary += unit;
}
t1_reg = lw1_unary;
}
}
rw1_unary = rw1_unary.split('').reverse().join('');
console.log(rw1_unary);
}

How to infinity spin on slot machine jQuery and stop it after do some action?

I have 2 option in radio input
Tab screen to stop in 0.5 sec -> So I complete this solution.
Tab screen to stop immediately. I want it spin after I press the submit button and it stops after I tab the screen.
Here is my fiddle here: https://jsfiddle.net/7det89o6/3/
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
}
});
}
<script type="text/javascript">
var reeling_time = 500;
var stop_spinning_time_difference = 350;
var start_spinning_time = 0;
var currency_symbol = "$";
var isInfinity = false;
$(document).ready(function() {
$(document).on('show.bs.modal', '.modal', function() {
function valRadioFunc() {
var valRadio = $('input[name=radio]:checked', '#form-select').val();
return valRadio;
}
$("#submit-btn").click(function() {
var cond = valRadioFunc();
if (cond == 1) {
$('.reel-container:first').slotMachine('00' + 1).toString();
// one click
$(".bg-img").one("click", function() {
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
} else if (cond == 2) {
$('.reel-container:first').slotMachine('00' + 1).toString();
isInfinity = true;
// one click
$(".bg-img").one("click", function() {
reeling_time = 0;
isInfinity = false;
$('.reel-container:first').slotMachine(randGen());
});
}
});
});
});
function randGen() {
var minRange = 1;
var maxRange = 999;
var randNum = (Math.floor(Math.random() * maxRange) + minRange).toString();
if (randNum.toString().length == 3) {
return randNum;
} else if (randNum.toString().length == 2) {
return "0" + randNum;
} else if (randNum.toString().length == 1) {
reeling_time = 0;
return "00" + randNum;
}
}
function collision($div1, $div2) {
var x1 = $div1.offset().left;
var w1 = 40;
var r1 = x1 + w1;
var x2 = $div2.offset().left;
var w2 = 40;
var r2 = x2 + w2;
if (r1 < x2 || x1 > r2) return false;
return true;
}
$.fn.slotMachine = function(my_number) {
var $parentSlot = this;
var hidden_reels_html = '';
var hidden_reels_array = [];
var numberFormat = function number_format(number) {
number = (number + '');
return number;
}
for (var $j = 0; $j <= 9; $j++) {
hidden_reels_array[$j] = "";
for (var $i = 0; $i <= 9; $i++) {
hidden_reels_array[$j] += '<div class="reel-symbol' + ($i == 0 ? ' reel-loop' : '') + '">' + (($j + $i) % 10) + '</div>';
}
}
var transformNumberToArrayPlusDollar = function(my_number) {
var my_scale = parseInt(my_number, 10) > 999 ? 0 : 2;
my_number = numberFormat(my_number, my_scale, ".", ",");
var my_number_array = my_number.split('');
// my_number_array.unshift(currency_symbol);
return my_number_array;
};
//Effect for the reel to go up and then down like it is pushed to spin
var effectBeforeSpin = function() {
$parentSlot.find('.main-reel-symbol').removeClass('reel-stop').addClass('reel-begin');
};
var slotMachine = function(my_number) {
var my_number_array = transformNumberToArrayPlusDollar(my_number);
var reels_html = '';
for (var $i = 0; $i < my_number_array.length; $i++) {
reels_html += '<div class="reel">' + hidden_reels_array[($i % 10)] + '</div>';
}
effectBeforeSpin();
var startSpinning = function() {
$parentSlot.html(reels_html);
var my_timer = reeling_time;
$.each(my_number_array, function(my_index, my_value) {
var next_value = /^[0-9]$/.test(my_value) ? (parseInt(my_value, 10) + 1) % 10 : "0";
var stopSpinning = function() {
$parentSlot.find('.reel:eq(' + my_index + ')')
.html("<div class='reel-symbol main-reel-symbol reel-stop'>" + my_value + "</div>")
.append("<div class='reel-symbol'>" + next_value + "</div>");
};
if(!isInfinity){
setTimeout(stopSpinning, my_timer);
}
my_timer += stop_spinning_time_difference;
});
};
setTimeout(startSpinning, start_spinning_time);
};
slotMachine(my_number);
return this;
};
$('.reel-container:first').slotMachine('00' + 1).toString();
</script>
I add one variable at top of JavaScript code.

Edit ajax loaded content

I have a HTML that loads a table from another page. I've got the CSS to work properly, but I can't edit the table using jQuery when it's pooled by the script, only when I have the table directly on the page. I'm guessing that maybe my changes are running before the load? I don't know..
I want to let you know that I'm not a programmer my self, but more of a curious person. I've searched around and found some things, but the lack of knowledge doesn't let me implement them. Hope you can help me.
The Script I use to read the data from the other page (p1.html)
<script type="text/javascript">
var TimerLoad, TimerChange;
var MaxNum, Rafraichir, Changement, ClassementReduit, ClassementReduitXpremier;
var UrlRefresh, UrlChange;
Rafraichir = 30000;
Changement = 150000;
MaxNum = 1;
ClassementReduit = 0;
ClassementReduitXpremier = 10;
function Load(url, target) {
var xhr;
var fct;
if (UrlChange) url = UrlRefresh;
else UrlRefresh = url;
UrlChange = 0;
if (TimerLoad) clearTimeout(TimerLoad);
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e2) {
try {
xhr = new XMLHttpRequest
} catch (e3) {
xhr = false
}
}
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
if (ClassementReduit == 0) document.getElementById(target).innerHTML = xhr.responseText;
else document.getElementById(target).innerHTML = ExtraireClassementReduit(xhr.responseText)
};
xhr.open("GET", url + "?r=" + Math.random(), true);
xhr.send(null);
fct = function() {
Load(url, target)
};
TimerLoad = setTimeout(fct, Rafraichir)
}
function ExtraireClassementReduit(Texte) {
var i, j, CompteurTD, CompteurTR;
var ColPosition, ColNumero, ColNom, ColEcart1er;
var Lignes;
var NouveauTexte;
CompteurTR = 0;
ColPosition = -1;
ColNumero = -1;
ColNom = -1;
ColEcart1er = -1;
Texte = Texte.substring(Texte.indexOf("<tr"));
Lignes = Texte.split("\r\n");
NouveauTexte = '<table width="100%" cellpadding="0" cellspacing="0">';
for (i = 0; i < Lignes.length; i++)
if (Lignes[i].substring(0, 3) == "<tr") {
NouveauTexte += Lignes[i];
CompteurTD = 0
} else if (Lignes[i].substring(0, 4) == "</tr") {
CompteurTR++;
if (CompteurTR == ClassementReduitXpremier + 1) break
} else if (Lignes[i].substring(0, 3) == "<td") {
if (CompteurTR == 0)
if (Lignes[i].indexOf("\"Id_Position\"") != -1) {
ColPosition = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else if (Lignes[i].indexOf("\"Id_Numero\"") != -1) {
ColNumero = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else if (Lignes[i].indexOf("\"Id_Nom\"") != -1) {
ColNom = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
} else {
if (Lignes[i].indexOf("\"Id_Ecart1er\"") != -1) {
ColEcart1er = CompteurTD;
NouveauTexte += Lignes[i].replace(/ width=".*"/i, "")
}
} else if (CompteurTD == ColPosition || CompteurTD == ColNumero || CompteurTD == ColNom || CompteurTD == ColEcart1er) NouveauTexte += Lignes[i];
CompteurTD++
}
NouveauTexte += "</table>";
return NouveauTexte
}
function Change() {
var Num, Index;
if (document.forms["Changement"].chkChangement.checked) {
Index = UrlRefresh.indexOf(".");
Num = parseInt(UrlRefresh.substring(1, Index)) + 1;
if (Num > MaxNum) Num = 1;
UrlRefresh = "p" + Num + ".html";
UrlChange = 1;
fct = function() {
Change()
};
TimerChange = setTimeout(fct, Changement)
} else if (TimerChange) clearTimeout(TimerChange)
};
</script>
Loading the table into the body
$(document).ready(Load('p1.html', 'result'));
The code I need to run after (it works with the table directly on page or even on a button, but I can't get to work on page load)
function show_hide_column(col_id, do_show) {
var stl;
if (do_show) stl = 'block'
else stl = 'none';
var tbl = document.getElementsByTagName('table')[0];
var index = document.getElementById(col_id).cellIndex;
var rows = tbl.getElementsByTagName('tr');
for (var row = 0; row < rows.length; row++) {
var cels = rows[row].getElementsByTagName('td')
cels[index].style.display = stl;
}
}
function hide() {
show_hide_column("Id_Position", false);
show_hide_column("Id_Equipe", false);
show_hide_column("Id_Vehicule", false);
}
I fired a console.log() message for every stage of the previous code, to know when exactly the table was added to the page, to then hide the columns. Got it to work.

JQuery / JavaScript Keyboard event

I have a typing speed test with a textarea and I have I paragraph split into spans. Every time the user hits space, it highlights the next span. Then I split the textarea val() and compare the two at the end. I have everything working except I cannot get the enter key to do what I want it to do. I need it to act like the space bar(in the background) and act as the enter key on screen.
$(function() {
//APPEARANCE
$('#error').hide();
$('#oldTextOne').hide();
$('#oldTextTwo').hide();
$('#oldTextThree').hide();
$('#oldTextFour').hide();
$('#oldTextFive').hide();
$('.linkBox').hover(function() {
$(this).removeClass('linkBox').addClass('linkHover');
}, function() {
$(this).removeClass('linkHover').addClass('linkBox');
});
//FUNCTIONALITY VARIABLES
var min = '5';
var sec = '00';
var realSec = 0;
var errorTest = "hasn't started yet";
var oldTextVal;
var para;
// PICK A RANDOM PARAGRAPH
function pickRandom() {
var date = new Date();
date = date.getTime();
date += '';
var dateSplit = date.split('');
var temp = dateSplit.length - 1;
var picker = dateSplit[temp];
if (picker === '0' || picker === '1') {
para = $('#oldTextOne').text();
}
else if (picker === '2' || picker === '3') {
para = $('#oldTextTwo').text();
}
else if (picker === '4' || picker === '5') {
para = $('#oldTextThree').text();
}
else if (picker === '6' || picker === '7') {
para = $('#oldTextFour').text();
}
else {
para = $('#oldTextFive').text();
}
var splitPara = para.split(' ');
for (i in splitPara) {
$('#oldTextBox').append('<span id="pw' + i + '">' + splitPara[i] + '</span> ');
}
}
pickRandom();
//FUNCTION FOR TIMER
//APPEARANCE
function show() {
$('#timer').text(min + ' : ' + sec);
}
show();
//COUNT-DOWN
var count = function() {
sec = +sec - 1;
sec += '';
realSec++;
if (+sec === -1) {
sec = '59';
min -= 1;
min += '';
}
if (sec.length === 1) {
sec = '0' + sec;
}
show();
if (sec === '00' && min === '0') {
clearInterval(run);
checkIt();
}
};
// TYPE THE TEXT INTO #TYPEDTEXTBOX
$('#pw0').addClass('green');
var lastLetter;
$('#typedTextBox').focus().keypress(function() {
if (errorTest === "hasn't started yet") {
errorTest = 'running';
run = setInterval(count, 1000);
}
//STOP ERRORS FROM PEOPLE HITTING SPACE BAR TWICE IN A ROW !!NOT WORKING IN IE8
var thisLetter = event.which;
if (lastLetter === 32 && event.which === 32) {
event.preventDefault();
}
lastLetter = thisLetter;
}).keyup(function() {
//STOP ERRORS FROM BACKSPACE NOT REGISTERING WITH KEYPRESS FUNCTION
if (event.which === 8) {
lastLetter = 8;
}
if (event.which === 13) {
?????????????????????????????????????????????
}
//SPLIT THE TYPED WORDS INTO AN ARRAY TO MATCH THE OLD TXT SPANS (TO HIGHLIGHT THE CURRENT WORD IN OLDTXT)
var typedWords = $(this).val().split(' ');
var temp = typedWords.length - 1;
var oldTemp = temp - 1;
var stopErrors = temp + 1;
$('span:nth(' + temp + ')').addClass('green');
$('span:nth(' + oldTemp + ')').removeClass('green');
$('span:nth(' + stopErrors + ')').removeClass('green');
//SCROLL
if (typedWords.length < 50) {
return;
}
else if (typedWords.length > 50 && typedWords.length < 100) {
$('#oldTextBox').scrollTop(30);
}
else if (typedWords.length > 100 && typedWords.length < 150) {
$('#oldTextBox').scrollTop(60);
}
else if (typedWords.length > 150 && typedWords.length < 200) {
$('#oldTextBox').scrollTop(90);
}
else if (typedWords.length > 200) {
$('#oldTextBox').scrollTop(120);
}
//KEEP FOCUS IN THE TYPING AREA
}).blur(function() {
if (errorTest !== 'done') {
$(this).focus();
}
});
//COMPARE
//MAKE AN ARRAY OF THE OLDTEXT
var oldWords = para.split(' ');
//FUNCTION TO DISPLAY RESULTS
var checkIt = function() {
errorTest = 'done';
var correct = 0;
var typed = $('#typedTextBox').val();
var typedWords = typed.split(' ');
$('#typedTextBox').blur();
for (i = 0; i < typedWords.length; i++) {
if (typedWords[i] === oldWords[i]) {
correct += 1;
}
}
var errors = typedWords.length - correct;
var epm = (errors / realSec) * 60;
var wpm = Math.round(( ($('#typedTextBox').val().length / 5 ) / realSec ) * 60);
var realWpm = Math.round(wpm - epm);
//SHOW RESULTS
$('#oldTextBox').html('<br><span id="finalOne">WPM : <strong>' + realWpm + ' </strong></span><span class="small">(error adjusted)</span><br><br><span id="finalTwo">You made ' + errors + ' errors </span><br><span id="finalThree">Total character count of ' + $('#typedTextBox').val().length + '</span><br><span id="finalFour">Gross WPM : ' + wpm + '</span>');
};
//STOP BUTTON APPEARANCE AND FUNCTIONALITY
$('#stop').mouseover(function() {
$(this).addClass('stopHover');
}).mouseout(function() {
$(this).removeClass('stopHover');
}).click(function() {
if (errorTest === 'running') {
checkIt();
clearInterval(run);
errorTest = 'done';
}
});
});
try this:
//ENTER KEY
if (event.which === 13) {
//event.stopPropagation(); or
event.preventDefault();
//simulate spacebar
$(window).trigger({type: 'keypress', which: 32, keyCode: 32});
}
#james - Thanks for the help. I found a better way of thinking about the problem. Instead of changing the enter key action, I changed the split function to var typedWords = typed.split(/[ \r\n]+/);

I am writing a hangman program in java script and need help getting the word to display if the player loosed

Here is the javascript code:
I need help getting the word to display after the player looses.
var can_play = true;
//this is the array of words
var words = new Array("VALIDATE", "DESIGN", "INPUT", "ARRAY", "OBJECT", "DOCUMENTATION", "JQUERY", "CALCULATE", "ABSOLUTE", "DREAMWEAVER", "BROWSER", "HTML", "CONCATINATION");
var display_word = "";
var used_letters = "";
var wrong_guesses = 0;
//this will allow the letters to be entered in only 1 time
function selectLetter(l) {
if (can_play == false) {
return;
}
if (used_letters.indexOf(l) != -1) {
return;
}
used_letters += l;
document.game.usedLetters.value = used_letters;
if (to_guess.indexOf(l) != -1) {
// this will display the correct letter guesses
pos = 0;
temp_mask = display_word;
while (to_guess.indexOf(l, pos) != -1) {
pos = to_guess.indexOf(l, pos);
end = pos + 1;
start_text = temp_mask.substring(0, pos);
end_text = temp_mask.substring(end, temp_mask.length);
temp_mask = start_text + l + end_text;
pos = end;
}
display_word = temp_mask;
document.game.displayWord.value = display_word;
if (display_word.indexOf("*") == -1) {
// this will display a message if you win
$('#win').html("Well done, you won!");
can_play = false;
}
} else {
// this will display the incorrect letter guesses
wrong_guesses += 1;
$('#wrong_guesses').html(wrong_guesses);
if (wrong_guesses == 6) {
// this will display a message if you loose
$('#win').html("Sorry, you have lost!");
can_play = false;
}
}
}
//this will reset the game to play again
function reset() {
selectWord();
document.game.usedLetters.value = "";
guessed_letters = "";
wrong_guesses = 0;
$('#win').html("");
$('#wrong_guesses').html("");
}
//this will have the computer select a word from my array
function selectWord() {
can_play = true;
random_number = Math.round(Math.random() * (words.length - 1));
to_guess = words[random_number];
// this will display mask
masked_word = createMask(to_guess);
document.game.displayWord.value = masked_word;
display_word = masked_word;
}
function createMask(m) {
mask = "";
word_length = m.length;
for (i = 0; i < word_length; i++) {
mask += "*";
}
return mask;
}
$('#win').html("Sorry, you have lost, the word was " + to_guess + "!");
You assigned the to be guessed word here:
to_guess = words[random_number];
You would learn much from posting your code to Code Review.

Categories