JQuery / JavaScript Keyboard event - javascript

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]+/);

Related

Disable required field when checkbox is selected to No

I am trying to disable option required when I select checkbox to "No"
So when I select "NO" and when I submit form I get a required message and It's return dropdown menu.
So in picture you can see better and you will understand the problem
When choice is selected to "NO"
https://i.imgur.com/kCFxTFA.jpg
When choice is selected to "YES"
https://i.imgur.com/cUPlZeb.jpg
When I selected choice NO and submit form I get required message
https://i.imgur.com/LvIxMM1.jpg
Source Code
Showing/Hidden content
$(document).ready(function () {
$("input[name$='Chapel']").click(function () {
var test = $(this).val();
if (test == 'No') {
$("div#hideChapel").hide();
}
else {
$("div#hideChapel").show();
}
});
});
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
Function for time and date validation
function dateValidation() {
if (document.getElementById('dateOfEvent').value == "")
document.getElementById("valDate").innerHTML = "<p>Date Field required.</p>";
else
document.getElementById("valDate").innerHTML = "";
}
function timeValidation() {
if (document.getElementById('TimeFrom').value == "")
{
document.getElementById("valTime").innerHTML = "<p>Time From Field required.</p>";
}
else
{
provjera();
document.getElementById("valTime").innerHTML = "";
}
}
Chapel Time validation
var isValidTIme = 1;
function chapelTime() {
var t = new Date();
var timeFrom = document.getElementById("TimeFrom").value;
var timeTo = document.getElementById("TimeTo").value;
var chapelTimeFrom = document.getElementById("ChapelTimeFrom").value;
var chapelTimeTo = document.getElementById("ChapelTimeTo").value;
d = t.getDate();
m = t.getMonth() + 1;
y = t.getFullYear();
//Convert time into date object
var d1 = new Date(m + "/" + d + "/" + y + " " + timeFrom);
var d2 = new Date(m + "/" + d + "/" + y + " " + timeTo);
var chd1 = new Date(m + "/" + d + "/" + y + " " + chapelTimeFrom);
var chd2 = new Date(m + "/" + d + "/" + y + " " + chapelTimeTo);
//Get timestamp
var t1 = d1.getTime();
var t2 = d2.getTime();
var cht1 = chd1.getTime();
var cht2 = chd2.getTime();
if (t2 < t1) {
var endDay = new Date(m + "/" + d + "/" + y + " " + "11:45 PM");
var startAnotherDay = new Date(m + "/" + d + "/" + y + " " + "12:00 AM");
if (cht1 > t2 && cht1 < t1) {
document.getElementById("valChapelTimeFrom").innerHTML = "<p>Chapel Time From must be between Event Time From and Event Time To values.</p>";
return false;
}
else if (cht1 < t1) {
document.getElementById("valChapelTimeFrom").innerHTML = "";
if (cht2 < cht1 || cht2 > t2) {
document.getElementById("valChapelTimeTo").innerHTML = "<p>Chapel Time To must be between Chapel Time From and Event Time To values.</p>";
return false;
}
else {
document.getElementById("valChapelTimeTo").innerHTML = "";
return true;
}
}
else if (cht2 < t1 && cht2 > t2) {
document.getElementById("valChapelTimeTo").innerHTML = "<p>Chapel Time To must be between Chapel Time From and Event Time To values.</p>";
return false;
}
else {
document.getElementById("valChapelTimeFrom").innerHTML = "";
document.getElementById("valChapelTimeTo").innerHTML = "";
return true;
}
}
else {
if (cht1 < t1 || cht1 > t2) {
document.getElementById("valChapelTimeFrom").innerHTML = "<p>Chapel Time From must be between Event Time From and Event Time To values.</p>";
return false;
}
else if (cht2 < t1 || cht2 > t2) {
document.getElementById("valChapelTimeFrom").innerHTML = "";
document.getElementById("valChapelTimeTo").innerHTML = "<p>Chapel Time To must be between Event Time From and Event Time To values.</p>";
return false;
}
else if (cht1 >= cht2) {
document.getElementById("valChapelTimeFrom").innerHTML = "";
document.getElementById("valChapelTimeTo").innerHTML = "";
document.getElementById("valChapelTimeTo").innerHTML = "<p>Chapel Time To must be greater then Chapel Time From.</p>";
return false;
}
else {
document.getElementById("valChapelTimeFrom").innerHTML = "";
document.getElementById("valChapelTimeTo").innerHTML = "";
return true;
}
}
}
There are rest of function for checking time and date
function provjera() {
if (chapelTime() == false || cocktailTime() == false || mainTime() == false) {
isValidTIme = 0;
}
else {
isValidTIme = 1;
}
}
function checkIfEmpty() {
if (document.getElementById("TimeFrom").value == "" || document.getElementById("TimeTo").value == "" || document.getElementById("ChapelTimeFrom").value == "" || document.getElementById("ChapelTimeTo").value == "" || document.getElementById("CocktailTimeFrom").value == "" || document.getElementById("CocktailTimeTo").value == "" || document.getElementById("MainTimeFrom").value == "" || document.getElementById("MainTimeTo").value == "") {
return false;
}
else {
provjera();
return true;
}
}
function provjeraBezChapela() {
if (cocktailTimeWithoutChapel() == false || mainTime() == false) {
isValidTIme = 0;
}
else {
isValidTIme = 1;
}
}
function checkIfEmptyWithoutChapel() {
if (document.getElementById("TimeFrom").value == "" || document.getElementById("TimeTo").value == "" || document.getElementById("CocktailTimeFrom").value == "" || document.getElementById("CocktailTimeTo").value == "" || document.getElementById("MainTimeFrom").value == "" || document.getElementById("MainTimeTo").value == "") {
return false;
}
else {
provjeraBezChapela();
return true;
}
}
I just only to disable required message when I choice "NO" and it should allow me to submit form.
Any suggestion ?
In your submit code you have to verify if the No option is selected, somethink like this:
if(document.getElementById('YesOption').checked) {
.........do something.......
}
if(document.getElementById('NoOption').checked) {
..... do other things without message....
}

Insert "/" in MM/YYYY textbox on keypress event

I want to enter a "/" when user enters MM(2 digit) so it will be like MM/YYYY.
I have done similar for credit card number input which insert a space after 4 digit on keypress.
let ccNumber = e.target.value.split(" ").join("");
if (ccNumber.length > 0) {
ccNumber = ccNumber.match(new RegExp('.{1,4}', 'g')).join(" ");
}
e.target.value = ccNumber;
Fiddle
This works with
Regular keyboard input
Copy/Cut/Paste
Selected text
Adding the /
Because you're programmatically adding the / character, you have to update the cursor position whenever that affects the new input value. This can be more than one character if the user is pasting something. Most of the code complexity revolves around this issue.
There are a lot of comments in the code explaining the various situations that come up because of the /.
Full Code
var date = document.getElementById('date');
date.addEventListener('keypress', updateInput);
date.addEventListener('change', updateInput);
date.addEventListener('paste', updateInput);
date.addEventListener('keydown', removeText);
date.addEventListener('cut', removeText);
function updateInput(event) {
event.preventDefault();
var string = getString(event);
var selectionStart = this.selectionStart;
var selectionEnd = this.selectionEnd;
var selectionLength = selectionEnd - selectionStart;
var sanitizedString = string.replace(/[^0-9]+/g, '');
// Do nothing if nothing is added after sanitization
if (sanitizedString.length === 0) {
return;
}
// Only paste numbers that will fit
var valLength = date.value.replace(/[^0-9]+/g, '').length;
var availableSpace = 6 - valLength + selectionLength;
// If `/` is selected it should not count as available space
if (selectionStart <= 2 && selectionEnd >= 3) {
availableSpace -= 1;
}
// Remove numbers that don't fit
if (sanitizedString.length > availableSpace) {
sanitizedString = sanitizedString.substring(0, availableSpace);
}
var newCursorPosition = selectionEnd + sanitizedString.length - selectionLength;
// Add one to cursor position if a `/` gets inserted
if (selectionStart <= 2 && newCursorPosition >= 2) {
newCursorPosition += 1;
}
// Previous input value before current cursor position
var valueStart = date.value.substring(0, this.selectionStart);
// Previous input value after current cursor position
var valueEnd = date.value.substring(this.selectionEnd, date.value.length);
var proposedValue = valueStart + sanitizedString + valueEnd;
// Remove anything that's not a number
var sanitized = proposedValue.replace(/[^0-9]+/g, '');
format(sanitized);
this.setSelectionRange(newCursorPosition, newCursorPosition);
}
function removeText(event) {
if (event.key === 'Backspace' || event.type === 'cut') {
event.preventDefault();
var selectionStart = this.selectionStart;
var selectionEnd = this.selectionEnd;
var selectionLength = selectionEnd - selectionStart;
// If pressing backspace with no selected text
if (selectionLength === 0 && event.type !== 'cut') {
selectionStart -= 1;
// Remove number from before `/` if attempting to delete `/`
if (selectionStart === 2) {
selectionStart -= 1;
}
}
var valueStart = date.value.substring(0, selectionStart);
var valueEnd = date.value.substring(selectionEnd, date.value.length);
// Account for added `/`
if (selectionStart === 2) {
selectionStart += 1;
}
var proposedValue = valueStart + valueEnd;
var sanitized = proposedValue.replace(/[^0-9]+/g, '');
format(sanitized);
this.setSelectionRange(selectionStart, selectionStart);
}
}
function getString(event) {
if (event.type === 'paste') {
var clipboardData = event.clipboardData || window.clipboardData;
return clipboardData.getData('Text');
} else {
return String.fromCharCode(event.which);
}
}
function format(sanitized) {
var newValue;
var month = sanitized.substring(0, 2);
if (sanitized.length < 2) {
newValue = month;
} else {
var year = sanitized.substring(2, 6);
newValue = month + '/' + year;
}
date.value = newValue;
}
<input id="date" type="text" maxlength="7">
Try:
var date = document.getElementById('date');
date.addEventListener('keypress', function (event) {
var char = String.fromCharCode(event.which),
offset = date.selectionStart;
console.log(offset)
if (/\d/.test(char) && offset < 7) {
if (offset === 2) {
offset += 1;
}
date.value = date.value.substr(0, offset) + char + date.value.substr(offset + 1);
date.selectionStart = date.selectionEnd = offset + 1;
}
if (!event.keyCode) {
event.preventDefault();
}
});
<input id="date" type="text" value="mm/yyyy" maxlength="6" size="6">
function keypress(elem) { // get Input
if (typeof elem == 'string') {
if (document.getElementById(elem)) elem = document.getElementById(elem);
if (typeof elem == 'string') elem = document.getElementsByName(elem).item(0);
}
const el = elem; //handle error if not found input
el.maxLength = 19;
el.addEventListener('keypress', function (e) {
const t = e.keyCode || e.which
if (t == 8 || (t > 47 && t < 58)) { // limit numeric characters and backspace
if (t != 8) {
if (el.value.length == 2) el.value += '/';
if (el.value.length == 5) el.value += '/';
if (el.value.length == 10) el.value += ' ';
if (el.value.length == 13) el.value += ':';
if (el.value.length == 16) el.value += ':';
}
} else {
e.preventDefault();
}
});}

curious css setting issue using setInterval

I'm trying to make a palindrome checker that changes the currently compared letters as it recurs.
Essentially, callback will do:
r aceca r
r a cec a r
ra c e c ar
rac e car
My JS Bin shows that the compared letters change green sometimes, but if you run it again, the letters won't change. Why is there a difference in results? It seems to sometimes run in Chrome, more often in FireFox, but it's all intermittent.
Code if needed (also available in JS Bin):
var myInterval = null;
var container = [];
var i, j;
var set = false;
var firstLetter, lastLetter;
$(document).ready(function(){
$("#textBox").focus();
$(document).click(function() {
$("#textBox").focus();
});
});
function pal (input) {
var str = input.replace(/\s/g, '');
var str2 = str.replace(/\W/g, '');
if (checkPal(str2, 0, str2.length-1)) {
$("#textBox").css({"color" : "green"});
$("#response").html(input + " is a palindrome");
$("#palindromeRun").html(input);
$("#palindromeRun").lettering();
if (set === false) {
callback(str2);
set = true;
}
}
else {
$("#textBox").css({"color" : "red"});
$("#response").html(input + " is not a palindrome");
}
if (input.length <= 0) {
$("#response").html("");
$("#textBox").css({"color" : "black"});
}
}
function checkPal (input, i, j) {
if (input.length <= 1) {
return false;
}
if (i === j || ((j-i) == 1 && input.charAt(i) === input.charAt(j))) {
return true;
}
else {
if (input.charAt(i).toLowerCase() === input.charAt(j).toLowerCase()) {
return checkPal(input, ++i, --j);
}
else {
return false;
}
}
}
function callback(input) {
$("#palindromeRun span").each(function (i, v) {
container.push(v);
});
i = 0;
j = container.length - 1;
myInterval = setInterval(function () {
if (i === j || ((j-i) === 1 && input.charAt(i) === input.charAt(j))) {
set = false;
window.clearInterval(myInterval);
container = [];
}
console.log(i + ' : ' + j);
$(container[i]).css({"color": "green"});
$(container[j]).css({"color": "green"});
i++;
j--;
}, 1000);
}
HTML:
<input type="text" id="textBox" onkeyup="pal(this.value);" value="" />
<div id="response"></div>
<hr>
<div id="palindromeRun"></div>
I directly pasted the jsLettering code in the JSBin, but here is the CDN if needed:
<script src="http://letteringjs.com/js/jquery.lettering-0.6.1.min.js"></script>
Change:
myInterval = setInterval(function () {
if (i === j) {
set = false;
window.clearInterval(myInterval);
container = [];
}
console.log(i + ' : ' + j);
to:
myInterval = setInterval(function () {
if (i >= j) {//Changed to prevent infinite minus
set = false;
window.clearInterval(myInterval);
container = [];
}
console.log(i + ' : ' + j);
demo

Where to place Mouse Enter and Mouse Leave in Javascript

I have the following script and am trying to add mouse enter and leave events on a slideshow such that when the mouse is over the image it won't switch to the next one, and once removed it continues.
I can get the slide to stop when the mouse is over but once the mouse is out the slideshow won't proceed.
I am unsure if these 2 lines are in the right place:
---> jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
---> jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
jQuery(function () {
jQuery('a').focus(function () {
this.blur();
});
SI.Files.stylizeAll();
slider.init();
});
---> var MOUSE_IN = false;
var slider = {
num: -1,
cur: 0,
cr: [],
al: null,
at: 10 * 1000, /* change 1000 to control speed*/
ar: true,
anim:'slide',
fade_speed:600,
init: function () {
if (!slider.data || !slider.data.length) return false;
var d = slider.data;
slider.num = d.length;
var pos = Math.floor(Math.random() * 1);
for (var i = 0; i < slider.num; i++) {
if(slider.anim == 'fade')
{
jQuery('#' + d[i].id).hide();
}
else{
jQuery('#' + d[i].id).css({
left: ((i - pos) * 1000)
});
}
jQuery('#slide-nav').append('<a id="slide-link-' + i + '" href="#" onclick="slider.slide(' + i + ');return false;" onfocus="this.blur();">' + (i + 1) + '</a>');
}
jQuery('img,div#slide-controls', jQuery('div#slide-holder')).fadeIn();
---> jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
---> jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
slider.text(d[pos]);
slider.on(pos);
if(slider.anim == 'fade')
{
slider.cur = -1;
slider.slide(0);
}
else{
slider.cur = pos;
window.setTimeout('slider.auto();', slider.at);
}
},
auto: function () {
if (!slider.ar) return false;
if(MOUSE_IN) return false;
var next = slider.cur + 1;
if (next >= slider.num) next = 0;
slider.slide(next);
},
slide: function (pos) {
if (pos < 0 || pos >= slider.num || pos == slider.cur) return;
window.clearTimeout(slider.al);
slider.al = window.setTimeout('slider.auto();', slider.at);
var d = slider.data;
if(slider.anim == 'fade')
{
for (var i = 0; i < slider.num; i++) {
if(i == slider.cur || i == pos) continue;
jQuery('#' + d[i].id).hide();
}
if(slider.cur != -1){
jQuery('#' + d[slider.cur].id).stop(false,true);
jQuery('#' + d[slider.cur].id).fadeOut(slider.fade_speed);
jQuery('#' + d[pos].id).fadeIn(slider.fade_speed);
}
else
{
jQuery('#' + d[pos].id).fadeIn(slider.fade_speed);
}
}
else
{
for (var i = 0; i < slider.num; i++)
jQuery('#' + d[i].id).stop().animate({
left: ((i - pos) * 1000)
},
1000, 'swing');
}
slider.on(pos);
slider.text(d[pos]);
slider.cur = pos;
},
on: function (pos) {
jQuery('#slide-nav a').removeClass('on');
jQuery('#slide-nav a#slide-link-' + pos).addClass('on');
},
text: function (di) {
slider.cr['a'] = di.client;
slider.cr['b'] = di.desc;
slider.ticker('#slide-client span', di.client, 0, 'a');
slider.ticker('#slide-desc', di.desc, 0, 'b');
},
ticker: function (el, text, pos, unique) {
if (slider.cr[unique] != text) return false;
ctext = text.substring(0, pos) + (pos % 2 ? '-' : '_');
jQuery(el).html(ctext);
if (pos == text.length) jQuery(el).html(text);
else window.setTimeout('slider.ticker("' + el + '","' + text + '",' + (pos + 1) + ',"' + unique + '");', 30);
}
};
if (!window.SI) {
var SI = {};
};
SI.Files = {
htmlClass: 'SI-FILES-STYLIZED',
fileClass: 'file',
wrapClass: 'cabinet',
fini: false,
able: false,
init: function () {
this.fini = true;
var ie = 0
if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) {
return;
}
this.able = true;
var html = document.getElementsByTagName('html')[0];
html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
},
stylize: function (elem) {
if (!this.fini) {
this.init();
};
if (!this.able) {
return;
};
elem.parentNode.file = elem;
elem.parentNode.onmousemove = function (e) {
if (typeof e == 'undefined') e = window.event;
if (typeof e.pageY == 'undefined' && typeof e.clientX == 'number' && document.documentElement) {
e.pageX = e.clientX + document.documentElement.scrollLeft;
e.pageY = e.clientY + document.documentElement.scrollTop;
};
var ox = oy = 0;
var elem = this;
if (elem.offsetParent) {
ox = elem.offsetLeft;
oy = elem.offsetTop;
while (elem = elem.offsetParent) {
ox += elem.offsetLeft;
oy += elem.offsetTop;
};
};
var x = e.pageX - ox;
var y = e.pageY - oy;
var w = this.file.offsetWidth;
var h = this.file.offsetHeight;
this.file.style.top = y - (h / 2) + 'px';
this.file.style.left = x - (w - 30) + 'px';
};
},
stylizeById: function (id) {
this.stylize(document.getElementById(id));
},
stylizeAll: function () {
if (!this.fini) {
this.init();
};
if (!this.able) {
return;
};
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1) this.stylize(input);
};
}
};
(function (jQuery) {
jQuery.fn.pngFix = function (settings) {
settings = jQuery.extend({
blankgif: 'blank.gif'
},
settings);
var ie55 = (navigator.appName == 'Microsoft Internet Explorer' && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf('MSIE 5.5') != -1);
var ie6 = (navigator.appName == 'Microsoft Internet Explorer' && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf('MSIE 6.0') != -1);
if (jQuery.browser.msie && (ie55 || ie6)) {
jQuery(this).each(function () {
var bgIMG = jQuery(this).css('background-image');
if (bgIMG.indexOf(".png") != -1) {
var iebg = bgIMG.split('url("')[1].split('")')[0];
jQuery(this).css('background-image', 'none');
jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='" + settings.sizingMethod + "')";
}
});
}
return jQuery;
};
})(jQuery);
jQuery(function () {
if (jQuery.browser.msie && jQuery.browser.version < 7) {
}
});
The position of both lines is fine, they just add an event handler to the mouse in/out event. The problem you experience is actually in tha auto function, if you note, at the end of the init function you have:
window.setTimeout('slider.auto();', slider.at)
This line makes a call to the auto function after a slider.at time (which is 10 seconds in your example), the auto function checks if MOUSE_IN is set to true, if it's not, then calls the slide function, then in the slide function you have another call to the auto function:
slider.al = window.setTimeout('slider.auto();', slider.at);
But once you set the MOUSE_IN variable to true the auto function simply returns and it stop the execution of further slide functions, to solve this, you may want to either handle the MOUSE_IN logic in the slide function, or before returning false in the auto function, call with a time out the auto function again.
Thought this would work but it doesnt, the mouseleave eventdoesnt seem to fire.
jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
while(MOUSE_IN==true)
{
jQuery('#slider-holder').mouseenter(function(){MOUSE_IN = true;});
jQuery('#slider-holder').mouseleave(function(){MOUSE_IN = false;});
}

Adding price to total when checkbox is selected

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

Categories