Javascript Add two Integer Variables? - javascript

So I am trying to create something where when a user clicks a div element, it adds a number to a total, sort of like a checkout system.
I have written the following javascript
JS
var optionOne = 5;
var optionTwo = 10;
var basePrice = 0;
function doMath() {
$("#option1checkout").click(function() {
// Add optionOne to basePrice
});
$("#option1cancel").click(function() {
// Don't do anything to basePrice
});
$("#option2checkout").click(function() {
// Add optionTwo to basePrice
});
$("#option2cancel").click(function() {
// Don't do anything to basePrice
});
};
I want it to add option 1 and 2 to basePrice whenever they click the option1checkout or option2checkout div element and do nothing when they click the cancel div elements.
I just feel like if I just do "basePrice + optionOne;" in the click functions it would be manual and not actually adding the integer values.
Any other way to do this?

What wrong with this approach:
var mousePrice = 5;
var coverPrice = 10;
var mouseSelected=0;
var coverSelected=0;
var basePrice = 500;
function doMath() {
$("#mouse").click(function() {
basePrice+=mousePrice;
});
$("#omouseCancel").click(function() {
if(mouseSelected>0){
basePrice-=(mousePrice*mouseSelected);
}
});
$("#cover").click(function() {
basePrice+=coverPrice;
});
$("#coverCancel").click(function() {
if(coverSelected>0){
basePrice-=(coverPrice*coverSelected);
}
});
};

Related

Phantomjs update values of var?

I have the below phantomjs program where the website contains a drop down list ddlLevel3
var page = require('webpage').create();
page.onConsoleMessage = function(str) {
console.log(str);
}
var z=0;
var z_l=0;
var op1='#ddlDivision'
var op2='#ddlLevel1'
var op3='#ddlLevel2'
var op4='#ddlLevel3'
function selectOption(selector, optionIndex) {
page.evaluate(function(selector, optionIndex){
var op4='#ddlLevel3'
var sel = document.querySelector(selector);
var sel4 = document.querySelector(op4);
sel.selectedIndex = optionIndex;
var event = document.createEvent("UIEvents"); // See update below
event.initUIEvent("change", true, false);
sel.dispatchEvent(event);
this.dispatchEvent(event);
z_l=sel4.length;
console.log("len: "sel4.length+" "+z_l);
}, selector, optionIndex);
}
page.open(...{
function loop4 () {
selectOption(op4,z);
window.setTimeout(function () {
go();
z++;
if (z < z_l) {
loop4();
}
}, 3000);
}
loop4();
});
I am trying to run loop4(). But the value of z_l is not changing from '0'.
In line console.log("len: "sel4.length+" "+z_l); Here values is proper.
But its not reflected back in loop4() in if (z < z_l), and remains 0 always.
What am I doing wrong?
I I wanted to get the value of z_l updated.I just need to use page.evaluate and assign it to z_l as below. Just made these changes in loop4().
function loop4 () {
var z_l = page.evaluate(function() {
var op4='#ddlLevel3'
return document.querySelector(op4)
});
selectOption(op4,z);
.
.
.
}

How to change slider value on dat.GUI and how to reset dat.GUI

1) I'm working on a dat.GUI application on which I have 2 sliders. I want to reset one when the other is changed. For example :
var FizzyText = function() {
this.slider1 = 0;
this.slider2 = 0;
};
var gui = new dat.GUI();
var text = new FizzyText();
var slider1 = gui.add(text, 'slider1', 0, 5);
var slider2 = gui.add(text, 'slider2', 0, 5);
slider1.onChange(function(value){
console.log(value);
text.slider2 = 0; // this doesn't work
});
slider2.onChange(function(value){
console.log(value);
text.slider1 = 0; // this doesn't work
});
This is just an example but it is very important that the slider is reseted or set to its default value (in FizzyText).
The example above comes from https://workshop.chromeexperiments.com/examples/gui/#9--Updating-the-Display-Automatically where I can't automatically update the slider
2) I want to add a reset button in which all sliders will be reseted. But with the previous answer I'd be able to reset all values
I found the answer :
gui.__controllers is and array of controllers. So I just added something like that :
var FizzyText = function () {
this.slider1 = 0;
this.slider2 = 0;
};
var gui = new dat.GUI();
var text = new FizzyText();
var slider1 = gui.add(text, 'slider1', 0, 5);
var slider2 = gui.add(text, 'slider2', 0, 5);
/* Here is the update */
var resetSliders = function (name) {
for (var i = 0; i < gui.__controllers.length; i++) {
if (!gui.__controllers.property == name)
gui.__controllers[i].setValue(0);
}
};
slider1.onChange(function (value) {
console.log(value);
resetSliders('slider1');
});
slider2.onChange(function (value) {
console.log(value);
resetSliders('slider2');
});
It's best to reset dat.GUI's values by using the controller's .initialValue instead of hard coding it, so the following would be preferable: gui.__controllers[i].setValue(gui.__controllers[i]);
You can reset all of a GUI's controllers by using gui.__controllers.forEach(controller => controller.setValue(controller.initialValue));

How to Set the value of an angular variable to another variable dynamically

I have a slideshow on my website with left and right buttons.
Like this (http://i.prntscr.com/863ad10cfd4e4f1ea9b90721cc6582e8.png).
I am using angular to change the image on left and right.
As you can see in the function I increase the value
/*SlideShow Pictures*/
$scope.picture_1 = "./images/photos/watch.jpg";
$scope.picture_2 = "./images/photos/watch.jpg";
$scope.picture_3 = "./images/photos/watch.jpg";
$scope.picture_4 = "./images/photos/watch.jpg";
$scope.picture = $scope.picture_1;
$scope.picture_value = 1;
$scope.image_change_right = function () {
if ($scope.picture_value < 4)
{
$scope.picture_value = $scope.picture_value + 1;
$scope.picture = ('$scope.picture_' + $scope.picture_value);
console.log($scope.picture_value);
}
else{
$scope.picture_value = 1;
$scope.picture = ('$scope.picture_' + $scope.picture_value);
console.log($scope.picture_value);
}
}
Above is the function called for button right press.
The function increases the variable by 1 and adds it to the string to call the new variable. In the console log it looks great! However I think it is only showing as a string --- it is not actually setting the value of scope.picture to the variable.
How can I set this to not be a string but as a valid variable?
Thanks everyone!
A better way would be like this:
The Controller:
// The array of picture links.
$scope.pictures = [
"./images/photos/watch.jpg",
"./images/photos/watch.jpg",
"./images/photos/watch.jpg",
"./images/photos/watch.jpg"
];
$scope.current = 0; // Initialize the current pictures place in the array.
$scope.picture = $scope.pictures[$scope.current]; // Set the current picture.
// The direction is either 1 or -1;
$scope.changePicture = function (direction) {
$scope.current += direction; // add or remove one depending on direction.
$scope.current %= $scope.pictures.length; // Normalize the number based on the length of the pictures array.
console.log($scope.picture);
}
The Html:
<img src="{{picture}}">
<button ng-click="changePicture(1)">Next</button>
<button ng-click="changePicture(-1)">Previous</button>
Why don't you use an array with image links like this?
/*SlideShow Pictures*/
$scope.pictures = ["./images/photos/watch.jpg", "./images/photos/watch.jpg", "./images/photos/watch.jpg", "./images/photos/watch.jpg"];
$scope.picture = $scope.pictures[0];
$scope.picture_value = 0;
$scope.image_change_right = function () {
if ($scope.picture_value < 4)
{
$scope.picture_value = $scope.picture_value + 1;
$scope.picture = $scope.pictures[$scope.picture_value];
console.log($scope.picture_value);
}
else{
$scope.picture_value = 0;
$scope.picture = $scope.pictures[$scope.picture_value];
console.log($scope.picture_value);
}
}

Change images randomly on click without repeating

I found this code on Stack Overflow: change images on click.
And it works for me. I want it to be random, but how can i prevent it from repeating the images. It should first repeat the images, when the user has clicked through all images.
I have made an JSfiddle with my code: http://jsfiddle.net/gr3f4hp1/
JQuery code:
var images = ["02.jpg","03.jpg","01.jpg"];
$(function() {
$('.change').click(function(e) {
var image = images[Math.floor(Math.random()*images.length)];
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
});
});
});
Keep track of the numbers that you have generated, and if its a repeat then get a new number.
You can Work Around This
var usedImages = {};
var usedImagesCount = 0;
function displayImage(){
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]){
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length){
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
you can try this code .
var images = ["02.jpg","03.jpg","01.jpg"];
var imagecon = [];
$(function() {
$('.change').click(function(e) {
if(images.length == 0) { // if no image left
images = imagecon; // put all used image back
imagecon = []; // empty the container
}
var index = Math.floor(Math.random()*images.length);
var image = images[index];
imagecon.push(image); // add used image
images.splice(index,1); // remove it to images
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
});
});
});
you could add a class to every image that appears like:
image.addClass("viewed")
and write an if statement that show the image only if it hasn't the class viewed:
if(!image.hasClass(viewed)){
(show the image methods);
image.addClass("viewed")
}
I'm not going to make all the code for you, just try this way, learn, fail, success, have fun! :D
Try this image change according to imgCnt variable.
var images = ["01.jpg","02.jpg","03.jpg","01.jpg"];
var imgCnt=1;
$(function() {
$('.change').click(function(e) {
// var image = images[Math.floor(Math.random()*images.length)];
if(imgCnt >= images.length){
imgCnt=0;
}
var image =images[imgCnt];
// alert(image);
$('#bg').parent().fadeOut(200, function() {
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
imgCnt++;
});
});
});
Demo
There are lots of method here i just push the value of visited image in to Visited array
Campate two array show only differ element
var images = ["02.jpg","03.jpg","01.jpg"];
var visited = [];
$(function() {
$('.change').click(function(e) {
var image = images[Math.floor(Math.random()*images.length)];
visited.push(image);
$('#bg').parent().fadeOut(200, function() {
y = jQuery.grep(images, function(value) {
if(jQuery.inArray(value, visited) == -1){
$('#bg').attr('src', 'items/'+image);
$(this).fadeIn(200);
}
});
} });
});
});
I hopes its help

Javascript for loop doesn't work (adding numbers to a total)

I am using Jasmine for JS testing, and unfortunately I can't get the following test to pass.
it('should know the total game score', function() {
frame1 = new Frame;
frame2 = new Frame;
game = new Game;
frame1.score(3, 4);
frame2.score(5, 5);
expect(game.totalScore()).toEqual(17)
});
The error message I get is as follows: Error: Expected 0 to equal 17.
The code is as follows:
function Game() {
this.scorecard = []
};
Game.prototype.add = function(frame) {
this.scorecard.push(frame)
};
// Why is this not working!!???
Game.prototype.totalScore = function() {
total = 0;
for(i = 0; i < this.scorecard.length; i++)
{
total +=this.scorecard[i].rollOne + this.scorecard[i].rollTwo;
}
return total;
};
function Frame() {};
Frame.prototype.score = function(first_roll, second_roll) {
this.rollOne = first_roll;
this.rollTwo = second_roll;
return this
};
Frame.prototype.isStrike = function() {
return (this.rollOne === 10);
};
Frame.prototype.isSpare = function() {
return (this.rollOne + this.rollTwo === 10) && (this.rollOne !== 10)
};
Adding the numbers together manually seems to work e.g. total = game.scorecard[0].rollOne + this.scorecard[0].rollTwo , but the for loop (even though it looks correct) doesn't seem to work. Any help would be greatly appreciated :)
I am not pretty sure, but it seems that you are not calling the "Add" method, so no data is added to the scorecard.
You have to add the Frames to your game i guess
it('should know the total game score', function () {
frame1 = new Frame;
frame2 = new Frame;
game = new Game;
// those lines are missing
game.add(frame1);
game.add(frame2);
frame1.score(3, 4);
frame2.score(5, 5);
expect(17).toEqual(game.totalScore())
});
otherwise, the scorecard-array is empty and the total score is therefore equal to 0.
missing (so no data is added to the scorecard.)
game.Add(frame1);
game.Add(frame2);

Categories

Resources