Can't get form total cost - javascript

So I have a form with two dropdowns. The first dropdown is the options, and the other is more options. So it's like a mix and match, now I want to calculate the total from the two selected dropdowns. Here's what I got going
var repairCost = new Array();
repairCost["none_repair"] = 0;
repairCost["minor"] = 10;
repairCost["major"] = 20;
repairCost["extreme"] = 30;
var colorCost = new Array();
colorCost["none_color"] = 0;
colorCost["single_portrait"] = 10;
colorCost["group_scene"] = 20;
$("#repair_drop").change(function (event) {
getRepair();
function getRepair(){
var repair = 0;
var form = document.forms["myform"];
var selectedRepair = form.elements["repair_drop"];
repair = repairCost[selectedRepair.value];
return repair
}
});
$("#colorize_drop").change(function (event) {
getColor();
function getColor(){
var color = 0;
var form = document.forms["myform"];
var selectedColor = form.elements["colorize_drop"];
color = colorCost[selectedColor.value];
return color
}
});
var timer1 = null;
clearTimeout(timer1);
timer1 = setTimeout(total, 500)
function total(){
var cost = getRepair() + getColor();
console.log(cost);
}
total();
I end up getting
Uncaught ReferenceError: getRepair is not defined
So for example I'd choose repairCost["minor"] and colorCost["group_scene"], then my result would be $30. I have a timer in there so it automatically calculates the total. Any ideas?

You defined the getRepair function inside another function. Therefore you cannot access it from outside. You have to define it outside the function to be able to access it, like so :
var repairCost = new Array();
repairCost["none_repair"] = 0;
repairCost["minor"] = 10;
repairCost["major"] = 20;
repairCost["extreme"] = 30;
var colorCost = new Array();
colorCost["none_color"] = 0;
colorCost["single_portrait"] = 10;
colorCost["group_scene"] = 20;
function getRepair(){
var repair = 0;
var form = document.forms["myform"];
var selectedRepair = form.elements["repair_drop"];
repair = repairCost[selectedRepair.value];
return repair;
}
function getColor(){
var color = 0;
var form = document.forms["myform"];
var selectedColor = form.elements["colorize_drop"];
color = colorCost[selectedColor.value];
return color;
}
$("#repair_drop").change(function (event) {
getRepair();
});
$("#colorize_drop").change(function (event) {
getColor();
});
var timer1 = null;
clearTimeout(timer1);
timer1 = setTimeout(total, 500)
function total(){
var cost = getRepair() + getColor();
console.log(cost);
}

Why are you declaring functions within your events, and then calling them from there? Either declare them outside the events, or just inline the code - don't do both.

Related

I just want to put some texts between tags using appendchild methods with Javascript

This code below is a javascript code to change texts and background properties from the body tag at the same time when the browser is clicked. I've just followed rules in w3school.com, actually, I'm doing the same as the examples do, but mine won't work and I've failed to find my fault. plz, help me.
var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);
body.style.backgroundColor = "#"+ number.toString();
bodyntext.style.color = "#"+ clnumber.toString();
}
Here's your problem
var bodyntext = document.getElementsByTagName("body").appendChild(helloDiv);
Please note that the javascript functions that have plural names often return arrays which is the case here
document.getElementsByTagName("body") returns an array and you are trying to perform an invalid action, that is append child, to this array. You need to access an element using index and then perform this action.
so using
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv); should fix your problem.
Use document.getElementsByTagName("body")[0] to achieve expected result, as getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, as a NodeList object.
var helloDiv = document.createElement("div");
var helloText = document.createTextNode("hi.");
helloDiv.appendChild(helloText);
var bodyntext = document.getElementsByTagName("body")[0].appendChild(helloDiv);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[0]+complementary[1]+complementary[2]).toString(16);
body.style.backgroundColor = "#"+ number.toString();
bodyntext.style.color = "#"+ clnumber.toString();
}
codepen - https://codepen.io/nagasai/pen/NLBXJE
Please refer this link for more details - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
I just change appendChild to document.body.appendChild(helloDiv) and added ID attribute for that div:
var helloDiv = document.createElement("div");
helloDiv.id = "myDIV";
document.body.appendChild(helloDiv);
var helloText = document.createTextNode("Click me");
helloDiv.appendChild(helloText);
var complementary = new Array();
var j = 0;
window.onclick = function(){
var background_color;
var body = document.getElementsByTagName("body")[0];
var helloText = document.getElementById("myDIV");
// var color = new Array();
var result = null;
var number = Math.round(Math.random()*0xFFFFFF);
for(var i = 0; i > 3; i++)
{
complementary[i] = (255-(number.slice(j,j+1).toString(10))).toString(16);
j = j + 2;
}
var clnumber = (complementary[6]+complementary[1]+complementary[2]).toString(16);
var clnumber2 = (complementary[0]+complementary[2]+complementary[6]).toString(11);
body.style.backgroundColor = "#"+ number.toString();
helloText.style.color = "#"+number.toString();
}

How do I determine which value has been called from an array, to use in another function?

I have the below code which is called onclick, and want to be able to show a second image after a few seconds, depending on which one is chosen from the array - so for example if 1.png is shown, then I want to show 1s.png, 2.png then show 2s.png etc
function displayImage () {
var img_name = new Array("images/1.png", "images/2.png", "images/3.png");
var l = img_name.length;
var rnd_no = Math.floor(l*Math.random());
document.getElementById("imgHolder").src = img_name[rnd_no];
}
How do I determine which image has been chosen from the array to then use in another function please ?
You're gonna need a global var for knowing that function is running for the first time or not.
var alreadyRandom = false;
function displayImage()
{
var img_name = new Array("images/1.png", "images/2.png", "images/3.png");
if(alreadyRandom)
{
// If the random for first time is done
var rnd_no = img_name.indexOf(document.getElementById("imgHolder").getAttribute('src'));
if(rnd_no === img_name.length-1)
{
// If the current image is the last one in array,
// go back to the first one
rnd_no = 0;
}
else
{
// Choose the next image in array
rnd_no++;
}
document.getElementById("imgHolder").src = img_name[rnd_no];
}
else
{
var l = img_name.length;
var rnd_no = Math.floor(l*Math.random());
document.getElementById("imgHolder").src = img_name[rnd_no];
alreadyRandom = true; // Tell the function not to random again
}
return img_name[rnd_no];
}
Demo: http://jsbin.com/kanejugahi/edit?html,js,console,output
Moreover, making the array global would make your function more efficient.
Hope this helps,
I think it's important you understand how Functions work in JavaScript and how scope works.
What you need to do is you need to expose that information so that both functions have access. You have the array of images defined and you have already determined the random number so just make them available by declaring them outside of the function so now these variables are available. Defining variables in the global scope is generally bad practice but this is simply for teaching.
var selectedImage; // defined outside so it is available for other functions
function displayImage() {
var img_name = new Array("images/1.png", "images/2.png", "images/3.png");
var rnd_no = Math.floor(img_name.length * Math.random());
selectedImage = img_name[rnd_no];
document.getElementById("imgHolder").src = selectedImage;
}
function anotherFunction() {
console.log(selectedImage);
}
As far as I understand the question, you can use a return and make the image array global.
var img_name = new Array("images/1.png", "images/2.png", "images/3.png");
var img_class = '';
//this function will return the index of the image in array
function displayImage () {
var l = img_name.length;
var rnd_no = Math.floor(l*Math.random());
document.getElementById("imgHolder").src = img_name[rnd_no];
return rnd_no;
}
var nextimage;
function showImages(){
//your logic to show the next image here
nextimage = (displayImage ()+1)%img_name.length;
var myVar = setInterval(function(){
if(img_class==''){
document.getElementById("imgHolder").src = img_name[nextimage];
img_class = 's';
}else{
var img_arr = img_name[nextimage].split(".");
if(img_arr.length===2){
document.getElementById("imgHolder").src = img_arr[0]+"s."+img_arr[1];
}
img_class = '';
nextimage = (nextimage+1)%img_name.length;
}
}, 1000);
}
var img_name = new Array("images/1.png", "images/2.png", "images/3.png");
var img_class = '';
//this function will return the index of the image in array
function displayImage () {
var l = img_name.length;
var rnd_no = Math.floor(l*Math.random());
document.getElementById("imgHolder").src = img_name[rnd_no];
return rnd_no;
}
var nextimage;
function showImages(){
//your logic to show the next image here
nextimage = (displayImage ()+1)%img_name.length;
var myVar = setInterval(function(){
if(img_class==''){
document.getElementById("imgHolder").innerHTML = img_name[nextimage];
img_class = 's';
}else{
var img_arr = img_name[nextimage].split(".");
if(img_arr.length===2){
document.getElementById("imgHolder").innerHTML = img_arr[0]+"s."+img_arr[1];
}
img_class = '';
nextimage = (nextimage+1)%img_name.length;
}
}, 1000);
}
showImages();
<div id="imgHolder"></div>
Mayve something like this?
var images = ["images/1.png", "images/2.png", "images/3.png"];
function displayImage () {
var dom = document.getElementById("imgHolder");
if ( images.indexOf(dom.src) >=0 ) {
dom.src = dom.src.replace(".png", "s.png"); // Seems like a stupid way to do this
return;
}
var l = images.length;
dom.src = images[Math.floor(l*Math.random())];
}

Google script - parse HTML from Website Forum - and Write Data to Sheet

I'm getting HTML from a forum url, and parsing the post count of the user from their profile page. I don't know how to write the parsed number into the Google spreadsheet.
It should go account by account in column B till last row and update the column A with count.
The script doesn't give me any errors, but it doesn't set the retrieved value into the spreadsheet.
function msg(message){
Browser.msgBox(message);
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Update")
.addItem('Update Table', 'updatePosts')
.addToUi();
}
function getPostCount(profileUrl){
var html = UrlFetchApp.fetch(profileUrl).getContentText();
var sliced = html.slice(0,html.search('Posts Per Day'));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
return postCount;
}
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var accountSheet = spreadSheet.getSheetByName("account-stats");
var statsLastCol = statsSheet.getLastColumn();
var accountCount = accountSheet.getLastRow();
var newValue = 0;
var oldValue = 0;
var totalNewPosts = 0;
for (var i=2; i<=accountCount; i++){
newValue = parseInt(getPostCount(accountSheet.getRange(i, 9).getValue()));
oldValue = parseInt(accountSheet.getRange(i, 7).getValue());
totalNewPosts = totalNewPosts + newValue - oldValue;
accountSheet.getRange(i, 7).setValue(newValue);
statsSheet.getRange(i,statsLastCol).setValue(newValue-todaysValue);
}
if(showAlert==false){
return 0;
}
msg(totalNewPosts+" new post found!");
}
function valinar(needle, haystack){
haystack = haystack[0];
for (var i in haystack){
if(haystack[i]==needle){
return true;
}
}
return false;
}
The is the first time I'm doing something like this and working from an example from other site.
I have one more question. In function getPostCount I send the function profileurl. Where do I declare that ?
Here is how you get the URL out of the spreadsheet:
function getPostCount(profileUrl){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getSheetByName("List1");
var getNumberOfRows = thisSheet.getLastRow();
var urlProfile = "";
var sliced = "";
var A_Column = "";
var arrayIndex = 0;
var rngA2Bx = thisSheet.getRange(2, 2, getNumberOfRows, 1).getValues();
for (var i = 2; i < getNumberOfRows + 1; i++) { //Start getting urls from row 2
//Logger.log('count i: ' + i);
arrayIndex = i-2;
urlProfile = rngA2Bx[arrayIndex][0];
//Logger.log('urlProfile: ' + urlProfile);
var html = UrlFetchApp.fetch(urlProfile).getContentText();
sliced = html.slice(0,html.search('Posts Per Day'));
var postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
Logger.log('postCount: ' + postCount);
A_Column = thisSheet.getRange(i, 1);
A_Column.setValue(postCount);
};
}
You're missing var in front of one of your variables:
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
That won't work. Need to put var in front. var postCount = ....
In this function:
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
There is no array named arguments anywhere in your code. Where is arguments defined and how is it getting any values put into it?

How to disable button from being clicked before a function has finished in javascript

Okay, so I have a button without any Id but when it is clicked it starts a function called buttonClick. This function basically controls a slot machine(poke machine) it's images, winnings etc. Note, some code may not work but please disregard this and imagine it working. But how can I make it so that if the user clicks the play button before this function is finished it won't do anything but will still finish the function it's already doing? Sorry for the inconvenience of not having my full length code in here, but a sample of it.
function buttonClick(){
var pic = new Array("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg");
var ex1 = pic[Math.floor(Math.random()*pic.length];
var ex2 = pic[Math.floor(Math.random()*pic.length];
var ex3 = pic[Math.floor(Math.random()*pic.length];
var moveImg = new Array("1.gif","2.gif","3.gif");
var timer = new Array("1000","5000","500","2000");
var time = Math.floor(Math.random()*4);
if (document.getElementById('coins').value > 0){
document.getElementById('coins').value -= 1;
pic[0].src = moveImg[0];
pic[1].src = moveImg[1];
pic[2].src = moveImg[2];
setTimeout(function(){
pic[0].src = ex1;
pic[1].src = ex2;
pic[2].src = ex3;
},timer[time])
}
else{
alert('Error insufficient tokens');
}
}
var in_progress = false;
function buttonClick(){
if(!in_progress){
var pic = new Array("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg");
var ex1 = pic[Math.floor(Math.random()*pic.length];
var ex2 = pic[Math.floor(Math.random()*pic.length];
var ex3 = pic[Math.floor(Math.random()*pic.length];
var moveImg = new Array("1.gif","2.gif","3.gif");
var timer = new Array("1000","5000","500","2000");
var time = Math.floor(Math.random()*4);
if (document.getElementById('coins').value > 0){
in_progress = true;
document.getElementById('coins').value -= 1;
pic[0].src = moveImg[0];
pic[1].src = moveImg[1];
pic[2].src = moveImg[2];
setTimeout(function(){
in_progress = false;
pic[0].src = ex1;
pic[1].src = ex2;
pic[2].src = ex3;
},timer[time])
} else {
alert('Error insufficient tokens');
}
}
}
alternatively you can wrap the function in a closure to make the in_progress a private variable.
var buttonClick = (function(){
var in_progress = false;
return function(){
if(!in_progress){
var pic = new Array("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg");
var ex1 = pic[Math.floor(Math.random()*pic.length];
var ex2 = pic[Math.floor(Math.random()*pic.length];
var ex3 = pic[Math.floor(Math.random()*pic.length];
var moveImg = new Array("1.gif","2.gif","3.gif");
var timer = new Array("1000","5000","500","2000");
var time = Math.floor(Math.random()*4);
if (document.getElementById('coins').value > 0){
in_progress = true;
document.getElementById('coins').value -= 1;
pic[0].src = moveImg[0];
pic[1].src = moveImg[1];
pic[2].src = moveImg[2];
setTimeout(function(){
in_progress = false;
pic[0].src = ex1;
pic[1].src = ex2;
pic[2].src = ex3;
},timer[time])
} else {
alert('Error insufficient tokens');
}
}
};
})();

Adding integers to array on javascript

I'm developing an application that is supposed to draw some rectangles on a canvas. The idea is draw them by putting each one at the last's side - I mean, start drawing it where the other finishes.
I have created a button that takes the values from an input, that was the easy part. I add this values to an Array, but each time I push the button, the array is empty again. I've heard that I need an 'instance variable', but I'm quite lost right now.
Any help will be welcome.
this is the code
function corta() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var medida1 = document.getElementById('medida2').value;
var medida2 = document.getElementById('medida1').value;
var corte1 = Math.round(medida1);
var corte2 = Math.round(medida2);
var arrayAncho = [];
var arrayLargo = [];
var ancho = 0;
var largo = 0;
arrayLargo.push(medida2);
arrayAncho.push(medida1);
//ancho, largo
document.getElementById('medida2').onclick = function () { this.value = ''; };
document.getElementById('medida1').onclick = function () { this.value = ''; };
//metodo para el ancho
for (var i = 0; i < arrayAncho.length ; i++) {
ancho += arrayAncho[i];
}
if (arrayAncho.length == 1) {
ctx.fillStyle = "#58FA58";
ctx.fillRect(0, largo, corte1, corte2);
} else
if (medida1 > 122 - ancho) {
ctx.fillStyle = "#58FA58";
ctx.fillRect(ancho, largo, corte1, corte2);//ancho, largo
}
medida1 = 0;
medida2 = 0;
}
Every time you run the function you run
var arrayAncho = [];
var arrayLargo = [];
This makes them blank every time. You have to declare them outside of the function and only reference them inside the code block

Categories