I have two functions that are triggered whilst the user is inputting data. They essentially add up the values of the options they choose, and output them.
On this form, in particular, the options are already pre-populated. Because of this, the functions have not been triggered, leaving their calculation as null.
The functions are shown just above </body>
Functions:
$(calculateScore);
function calculateScore () {
var fields = $('.form-group #input').change(calculate);
function calculate () {
var score = 0;
fields.each(function () {
score += +$(this).val();
});
$('#score').html(score.toFixed(0));
}
}
$(calculateHiddenScore);
function calculateHiddenScore () {
var fields = $('.form-group #input').change(calculate);
function calculate () {
var score = 0;
fields.each(function () {
score += +$(this).val();
});
$('#hidden_score').val(score.toFixed(0));
}
}
Code placed underneath the functions to try and trigger them:
$(function () {
calculateHiddenScore();
calculateScore();
});
and I have also tried:
window.onload = function () {
calculateScore();
calculateHiddenScore();
};
How can I trigger these two functions when the page has loaded please? Many thanks.
DOM ready will not trigger an onchange event even if your items are pre-populated.
Therefore you have to modify a bit your script like:
function calculateScore() {
var fields = $('.form-group #input'); // Cache only!
function calculate() {
var score = 0;
fields.each(function() {
score += +$(this).val();
});
$('#score').html(score.toFixed(0));
$('#hidden_score').val(score.toFixed(0));
}
calculate(); // Calculate ASAP (on DOM ready)
fields.on("change", calculate); // and also on change
}
jQuery(function($) { // DOM is ready and $ alias secured
calculateScore(); // Trigger
// other jQuery code here
});
P.S: BTW even if the above is a bit improved, it makes not much sense to loop using each over a single ID #input element - I'll leave that to you...
Related
The following code tracks the number of clicks on the element and then submits the result to Facebook Pixel. However, the event is not triggered for some reason.
Thought it's a variable scope problem, changed countClicks to global but it didn't change anything.
$(document).ready(function () {
if(window.location.href.indexOf("products") > -1) {
var countClicks = 0;
$(".product-single__thumbnail-image").click(function () {
countClicks++;
});
function firePixelSlideshowView() {
fbq('trackCustom', "ProductSlideshowImageView", {
imageView: countClicks,
});
}
window.onbeforeunload = function () {
firePixelSlideshowView();
return null;
}
}
});
I solved the problem by using jQuery unload() function instead of vanilla Javascript and it worked.
I have two multiselect menus where I'm trying to get a total of how many children are present in each multiselct on load, then update the numbers, based on a click event which will push from one to the other, or vice versa.
The onload portion is working fine. I'm getting the results I'd expect and the counts are accurate.
The problem I'm having is updating both counts once the click event triggers. My counts never change.
Here's my code along with a fiddle:
var activeUser = $('.activeUsers');
var eligibleUser = $('.eligibleUsers');
var availableUserCount = $("#availableUsers option").length;
var eligibleUserCount = $("#eligibleUsers option").length;
activeUser.html(availableUserCount);
eligibleUser.html(eligibleUserCount);
$('#availableUsers').click(function () {
return !$('#availableUsers option:selected').remove().appendTo('#eligibleUsers');
activeUser.length(function() {
return availableUserCount();
});
eligibleUser.length(function() {
return eligibleUserCount();
});
});
$('#eligibleUsers').click(function () {
return !$('#eligibleUsers option:selected').remove().appendTo('#availableUsers');
activeUser.length(function() {
return availableUserCount();
});
eligibleUser.length(function() {
return eligibleUserCount();
});
});
http://jsfiddle.net/mujaji/8gkLyfe3/3/
What am I doing wrong?
There seems to be 3 problems with your code.
You are using return in the fist line of the click event. So the following code will never be executed (Get rid of that and only return if you cannot find any options)
There is no method called length for a div element. (Use .text() instead)
When you are returning the length inside the function return availableUserCount(); it will return you the cached value. (You need to reselect the element again)
So your code should technically look like this (further refactoring can still be made)
var activeUser = $('.activeUsers');
var eligibleUser = $('.eligibleUsers');
var availableUserCount = $("#availableUsers option").length;
var eligibleUserCount = $("#eligibleUsers option").length;
activeUser.html(availableUserCount);
eligibleUser.html(eligibleUserCount);
$('#availableUsers').click(function () {
!$('#availableUsers option:selected').remove().appendTo('#eligibleUsers');
activeUser.text(function() {
return $("#availableUsers option").length;
});
eligibleUser.text(function() {
return $("#eligibleUsers option").length;
});
});
$('#eligibleUsers').click(function () {
!$('#eligibleUsers option:selected').remove().appendTo('#availableUsers');
activeUser.text(function() {
return $("#availableUsers option").length;
});
eligibleUser.text(function() {
return $("#eligibleUsers option").length;
});
});
Check Fiddle
$("#availableUsers option").length doesn't dynamically change with the number of options. Once you set it up top, it's 40 forever. This does what you want:
$('#availableUsers').click(function () {
$('#availableUsers option:selected').remove().appendTo('#eligibleUsers');
activeUser.text($("#availableUsers option").length);
eligibleUser.text($("#eligibleUsers option").length);
});
Although it's not efficient to re-query every time when you could do
availableUserCount--; eligibleUserCount++;
And keep track of it manually.
Best solution (sic) :D
/*JQUERY FUNCTIONS*/
var activeUser = $('.activeUsers');
var eligibleUser = $('.eligibleUsers');
var eligibleUserCount = function(){eligibleUser.html($("#eligibleUsers option").length)};
var availableUserCount = function(){activeUser.html($("#availableUsers option").length)};
eligibleUserCount();
availableUserCount();
$('#availableUsers').click(function () {
$('#availableUsers option:selected').remove().appendTo('#eligibleUsers');
availableUserCount();
eligibleUserCount()
});
$('#eligibleUsers').click(function () {
$('#eligibleUsers option:selected').remove().appendTo('#availableUsers');
availableUserCount();
eligibleUserCount()
});
http://jsfiddle.net/8gkLyfe3/5/
Using return in the first line of the functions prevents any other code from executing in that block.
Check out my fiddle for a functionalized way to perform this
function setUserCounts(){
availableUserCount = $("#availableUsers option").length;
eligibleUserCount = $("#eligibleUsers option").length;
activeUser.html(availableUserCount);
eligibleUser.html(eligibleUserCount);
}
http://jsfiddle.net/8gkLyfe3/6/
Essentially, we add this function and then call it from within the click handlers, while also removing the
Hi I'm running a sum and multiplication script for some field input values to a form i made. How can I get this script to run on a button click so that after a user enters a new value they can click a update form button to run the calculations script and update the total sum.
<script>
var $form = $('#contactForm'),
$summands = $form.find('.sum1'),
$sumDisplay = $('#itmttl');
$form.delegate('.sum1', 'change', function ()
{
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum);
});
function multiply(one, two) {
if(one && two){
this.form.elements.tax.value = one * two;
} else {
this.style.color='blue';
}
}
</script>
Define a function and put the code you want to run inside it.
var doStuff = function () {
// do some stuff here
};
Select your button and call that function on click. If you're using an A or BUTTON tag you may want to prevent the default action, which I've included in this example.
$('.button').on('click', function (event) {
doStuff();
event.preventDefault();
});
This assumes that you're using jQuery 1.7+.
I made a control (numeric spinner up and down), to work in a table:
JSFIDDLE: http://jsfiddle.net/Leandro1981/wn8vd/1/
and I want simulate the "mousedown, increment while mouse button is helding" but I can't do it. I tried to mix it with the following and functional script:
JSFIDDLE: http://jsfiddle.net/Leandro1981/kKW85/
but I couldn't make it.
My last attempt here:
http://jsfiddle.net/Leandro1981/S8Zt9/1/
Maybe the wrong is the
timeout = setInterval(function () {
But I couldn't figure out. I'm using bootstrap 3, so I can't use some JQuery UI plugins...
Any help will be preciated!
Please comment below if you have any question, comment or anything to improve this question, and sorry for my english :)
Please be free to use my code/control in any way.
Thanks and kind regards
Write a factory to set up each control so you get a closure over the variables, now it's just a matter of being able to make it work given the relevant elements. For this, you'll need to
Listen for mousedown on the up and down nodes to set off the changes
Start a timeout loop to keep doing your change
Listen for mouseup on window to ensure you cancel the timeout loop (you may also want to listen for mouseout/loss of focus)
So all together,
function spinFactory(node, up, down) { // I wrote this vanilla :D
var spinning, delta;
window.addEventListener('mouseup', stopSpin);
function spin() {
node.value = +node.value + delta;
spinning = setTimeout(spin, 500);
}
function stopSpin() { // maybe also invoke this on mouseout/loss of focus
window.clearTimeout(spinning);
delta = 0;
}
up.addEventListener('mousedown', function spinUp() {
delta = 1;
spin();
});
down.addEventListener('mousedown', function spinDown() {
delta = -1;
spin();
});
}
// apply to your control, used a bit of jQuery to make life easier
$('.PNET-spinner').each(function () {
spinFactory(
this.getElementsByTagName('input')[0],
$(this).find('.btn:first-of-type')[0],
$(this).find('.btn:last-of-type')[0]
);
});
DEMO
I have updated the Fiddle here ... Please check this and it might helps you..
Script
$('.PNET-spinner .btn:first-of-type').on('mousedown', function (e) {
var timer, proxy = this;
timer = setInterval(function () {
increment(proxy);
}, 200);
$(document).one("mouseup", function () {
increment(proxy);
if (timer) clearInterval(timer);
});
});
$('.PNET-spinner .btn:last-of-type').on('mousedown', function () {
var timer, proxy = this;
timer = setInterval(function () {
decrement(proxy);
}, 200);
$(document).one("mouseup", function () {
decrement(proxy);
if (timer) clearInterval(timer);
});
});
function increment(proxy) {
var numupdown = $('.PNET-spinner input', $(proxy).closest("tr"));
var inputValue = parseInt($(numupdown).val(), 10);
inputValue++;
$(numupdown).val(inputValue);
}
function decrement(proxy) {
var numupdown = $('.PNET-spinner input', $(proxy).closest("tr"));
var inputValue = parseInt($(numupdown).val(), 10);
if (inputValue > 1) {
inputValue--;
$(numupdown).val(inputValue);
}
}
You simply need to take care of two things. First, your function to increment and decrement the value in the textbox should be called again and again till user do mouseout or mouseup. Second, make surethis has the right value in var numupdown = $('.PNET-spinner input', $(this).closest("tr"));
Following code shows how to do it for the increment button. Similar thing, you can implement for decrement button.
var timeout;
var inc = function () {
var myThis = this;
var numupdown = $('.PNET-spinner input', $(this).closest("tr"));
var inputValue = parseInt($(numupdown).val(), 10);
inputValue++;
console.log(inputValue);
$(numupdown).val(inputValue);
clearTimeout(timeout);
timeout = setTimeout(function(){
//http://stackoverflow.com/questions/3630054/how-do-i-pass-the-this-context-to-a-function
inc.apply(myThis, arguments);
}, 1000);
};
var incStop = function(){
clearTimeout(timeout);
}
$('.PNET-spinner .btn:first-of-type').on('mousedown', inc);
$('.PNET-spinner .btn:first-of-type').on('mouseup', incStop);
$('.PNET-spinner .btn:first-of-type').on('mouseout', incStop);
Check this DEMO here.
In my game I have a startGame() function which initializes all the key functions that start the game. At the beginning, you press the start button to take you to the game. Once the game is complete the restart button appears. When this is clicked it takes you back to the start screen, where the start button is.
Ideally I would like at this point to be able to click the start button for the second time, and a new game appear. The problem is that it brings the old game up. I have tried to use .empty, .queue and .dequeue and reset, but nothing seems to work.
How can I restart all the functions when the restart-button is clicked?
$(document).ready(function () {
successSound = $("#successSound")[0];
failSound = $("#failSound")[0];
moveSound = $("#moveSound")[0];
hitSound = $("#hitSound")[0];
missSound = $("#missSound")[0];
hintSound = $("#hintSound")[0];
hintPic = $("#hintPic")[0];
hintPicTitle = $("#hintPicTitle")[0];
bgMusic = $('#audio-bg')[0];
newGame();
//Click event to start the game
$(".start-btn-wrapper").click(function () {
startplay();
});
//Click event to restart the game
$(".restart-btn").click(function () {
restartplay();
});
Fiddle with script in: http://jsfiddle.net/rVaFs/
It will be much easier if you stop using globals: everything not prefixed with var (including functions).
If your startplay depends on initial DOM state, and it’s too difficult (or just takes too much time) to rewrite the code, you can just make a copy of that part of DOM before starting game and delete it on finish.
You could use the document.ready callback to reset everything back to it's original state, by naming the callback function:
$(document).ready(function reset()
{
//your code here
//note, you must ensure event handlers are unbound:
$('#reset').unbind('click').bind('click',reset);//<-- call main callback
});
Another thing you have to keep in mind is that you're creating a lot of implied globals, which could cause problems if you were to use the ready callback. To address this, do change these lines: successSound = $("#successSound")[0]; to var successSound = $("#successSound")[0];.
I created a function called resetGame() and cleared the DOM:
function resetGame() {
$(document).ready();
$('.table-container').empty();
$('.reveal-wrapper').empty();
$('.helper').removeClass('inactive');
$('.tiles-wrapper').removeClass('active');
$('.hint-container').removeClass('active');
$('td').addClass('highlight-problem');
$('.game').removeClass("active").removeClass('game-over').addClass('standby').addClass('transition');
$('.score').html("");
$(".next-question").removeClass('move-down');
$('.reveal-wrapper').removeClass('image' + randomNumber);
$(bgMusic).unbind();
score.right = 0;
score.wrong = 0;
}
function newGame() {
randomWord = [];
listOfWords = [];
attemptNumber = [];
completionNumber = [];
populationNumber = [];
gridSize = [];
createGrid();
backGroundImage();
dragEvent();
nextQuestion();
closeMessage();
replaySound();
$('.score').html("0/" + completionNumber);
$('.game').removeClass("standby").addClass('active').addClass('transition');
$(bgMusic).on('timeupdate', function () {
var vol = 1,
interval = 250;
if (bgMusic.volume == 1) {
var intervalID = setInterval(function () {
if (vol > 0) {
vol -= 0.05;
bgMusic.volume = vol.toFixed(2);
} else {
clearInterval(intervalID);
}
}, interval);
}
});
}
$(document).ready(function () {
successSound = $("#successSound")[0];
failSound = $("#failSound")[0];
moveSound = $("#moveSound")[0];
hitSound = $("#hitSound")[0];
missSound = $("#missSound")[0];
hintSound = $("#hintSound")[0];
hintPic = $("#hintPic")[0];
hintPicTitle = $("#hintPicTitle")[0];
bgMusic = $('#audio-bg')[0];
backGroundSound();
playBackGroundSound();
keyPress();
$(".start-btn-wrapper").click(function () {
newGame();
});
$(".restart-btn").click(function () {
resetGame();
});
});
I then called it in the restart-btn click event.