How do increment value while it being declared inside function - javascript

I have a small issue where i'm trying to increment/decrement the buttons in x steps this is all dynamic dependant on what ever the quantity step is, my code works fine when its increments of one because i am just using ++ there is no scope issue
I've tried a few things but no much luck i can't really declare it outside of the function as there is multiple input boxes and i'd need to do some sort of mapping to know which one relates to which input.
I know what the issue is its because of scoping im defining a variable inside a function but its not a simple thing to do it outside of it any other solutions to get past this without defining it outside ?
When i had it like this this.$refs[codeForRef][0].value++ it worked fine and would increment by one
increment: function(e) {
e.preventDefault();
var codeForRef = e.srcElement.id;
var test = parseInt(this.$refs[codeForRef][0].value, 10); //the value of the qty
test += this.dyQty //whatever it needs to go up in
},

what i understood from your question, this should work for you.
increment: function(e) {
e.preventDefault();
var codeForRef = e.srcElement.id;
var test = parseInt(this.$refs[codeForRef][0].value, 10); //the value of the qty
test += this.dyQty //whatever it needs to go up in
this.$refs[codeForRef][0].value = test;
}

Related

Problems with onclick / calculating a sum

Let me start by saying, that while I have some programming experiencing (some basic C from a college class and I once wrote a FORTRAN programm in college for a professor), I am utterly new to JS and beginning to get a bit frustrated.
For some reason, even after reading tutorials and watching several YouTube videos on objects, I seem unable to wrap my head around it. I understand the fundamentals and have no problems doing very basic stuff, like writing a loop that prints out increments on a HTML site, but every time I try something practical, I am completely at a loss.
Here is my current problem: I have created this HTML site that generates a shopping list. Basically, when I click on one of the buttons next to an item name, it adds that item to the list in the middle of my screen. Thanks to Google I found a piece of JavaScript code which, through try and error, I managed to tweak for this purpose:
<!-- click this button to add the item-->
<button onclick="myFunction('ITEM1', 100)" class="sidebarbuttons" >ITEM1 </button>
/* Create a List one line at a time- */
<script>
function myFunction( x, y ) {
var node = document.createElement("LI" );
var textnode = document.createTextNode(x);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
</script>
So far, so good. Now I want to get the net price for all the items. Which means, When I click the button, I want a function to add the price of that item to a variable and then display that variable in a field with
document.getElementById("result").innerHTML = total_sum;
Here's my question: how, oh my god, how do I do this? I thought I could add the following:
function myfunction(x,y){
var sum = 0;
var sum+=y;
}
document.getElementById("result").innerHTML = 'sum';
Obviously, this doesn't work at all. Can you please give me some hints what I have to do to make this work?
First of all,
please consider to study JavaScript better, because it's a falsy easy programming language and it's very dangerous to copy&paste without knowing the language. It's quite normal to read a lot, watch a lot and don't know where to start, and it's the main reason because people hates JavaScript: because we don't know well JavaScript. So consider to read the book series "You Don't Know" by Kyle Simpson.
About your question. You can add a variable to storage the sum of your items and when you click to an item, you can add to it:
var total_sum = 0;
function myFunction( x, y ) {
var node = document.createElement("LI" );
var textnode = document.createTextNode(x);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
showResults(y);
}
function showResults(price){
total_sum += parseFloat(price)
document.getElementById("result").innerHTML = total_sum;
}
JSBIN
Let me know ;)
So you are on the right track. Picking up where you left off in your last code block, there are few things you will need to change.
//declare the variable outside of the function... otherwise it will only be available to you within that function.
var totalSum = 0;
// then within your function you will be able to successfully add to the global totalSum variable
function calculateSum(x){
totalSum += x;
// and lastly... set the innerHTML within the function... which should equal the variable totalSum
document.getElementById("result").innerHTML = totalSum;
}
Hope this helps.

Why does this code create an infinite loop?

I have a JavaScript problem. I have a function that runs when I hit a button, the variables are changed via JavaScript. Everything in the function runs properly but this one last part:
else if (upgrade == "upgMiner4") {
var cost="500";
var qty="1";
var readCash=parseInt(document.getElementById("cash").innerHTML);
while (readCash >= cost) {
document.getElementById("cash").innerHTML += "-"+cost;
document.getElementById("cash").innerHTML = eval(document.getElementById("cash").innerHTML);
document.getElementById("gpt").innerHTML += "+"+qty;
document.getElementById("gpt").innerHTML = eval(document.getElementById("gpt").innerHTML);
}
}
When I run this code, it freezes and creates an infinite loop. I don't see the problem here, so I would like to know if you guys could help me, thanks!
-Zachucks
Your code inside the while loop does nothing to update readCash or cost, so if the condition (readCash >= cost) is true, this will never change, and the while loop will never exit.
I should add that a reader cannot tell what the evals are evaluating--so it's hard to be sure what is going on. However, notice you assign to readCash and cost exactly one time and that you never do this again. So why would it change?
Because you set readCash value only once and don't update it together with innerHTML with your div. That's why your loop doesn't end.
Working code:
while (readCash >= cost) {
document.getElementById("cash").innerHTML += "-"+cost;
document.getElementById("cash").innerHTML = eval(document.getElementById("cash").innerHTML);
document.getElementById("gpt").innerHTML += "+"+qty;
document.getElementById("gpt").innerHTML = eval(document.getElementById("gpt").innerHTML);
readCash = document.getElementById("cash").innerHTML;
}
neither readCash or cost variable are changing in the last while loop. That's why you're facing a loop. Probably you have to increment/decrement readCash or cost vars with a logic you're missing. Or maybe you don't actually need a while statement, but simply an if

dojo foreach function

I am quite new to dojo and I'm stuck with a problem here
I have a zend dojo form where I need to take sum of four elements and set the value to another element. I have assigned a class (score) to those four elements
".score" : {
"found" : function (ele) {
var widgetId = ele.getAttribute('widgetid');
dojo.connect(dijit.byId(widgetId),'onBlur', function(){
var sum = 0;
dojo.query('.score')
.forEach(function(ele){
var widgetId = ele.getAttribute('widgetid');
sum += parseInt(dijit.byId(widgetId).get('value'));
});
//***cannot get the value of sum here
dijit.byId('score_total').set('value', sum);
});
}
}
As commented I am unable to get the sum of those values outside the foreach. Is there any way to get the value out of the loop? Am I doing any thing wrong?
It seems that I had made a mistake in the code and since I am quite new to jscript I was unable to debug. foreach indeed is not a asynchronous and sum was being calculated just that the parseInt(dijit.byId(widgetId).get('value')) was returning not a number NaN hence I was unable to populate the form element, I simply added an if condition and it worked
if(parseInt(dijit.byId(widgetId).get('value'))){
sum = sum + parseInt(dijit.byId(widgetId).get('value'));
}
Sorry for the trouble
One thing to note... dojo.foreach is deprecated ...
http://livedocs.dojotoolkit.org/dojo/forEach
instead ... array.forEach
http://livedocs.dojotoolkit.org/dojo/_base/array#forEach
but i think you might also have a scoping issue as well.. try something like this..
var sum = 0;
var elements = dojo.query('.score');
array.forEach(elements, function(ele) {
var widgetId = ele.getAttribute('widgetid');
sum += parseInt(dijit.byId(widgetId).get('value'));
});
in your case, the parent context has the variable, so it will work as you have used it.
Just a side point that if you want to access the sum variable outside the parent context, you will need to use dojo.hitch or pass the context to dojo.forEach
http://www.ibm.com/developerworks/web/library/wa-aj-dojo/
see the section on "Setting method context"

Password Strength Meter

I'm trying to create my own JS Password Strength Meter.
It was working before but i didn't like how it worked so I tried using
{score +=10;}
Instead of just:
score++
This is my code:
http://jsfiddle.net/RSq4L/
Best Regards,
Shawn,
Hope someone can help
Multiple issues:
Your passwordStrength() function was not defined in the global scope in the jsFiddle so it wasn't getting called. This is probably an artifact of how you set up the jsFiddle, perhaps not an issue in your real code.
The method of getting the appropriate ratingMsg will not work because you don't have array values for every possible score so many scores will generate an "undefined" ratingMsg.
Your CSS classes are also sparse so there are many score values that they will not match for either and no appropriate CSS class/style will be in effect. If you want a specific class for each rating value, then perhaps you should put the classname in the ratings array so it can be fetched from there along with the ratingsMsg.
For the first issue, in your jsFiddle, you also have to make sure the password processing function is defined in the global scope. The way your jsFiddle is set up, it is not (it's in the onload handler). You can fix this in the jsFiddle by just setting the first drop-down in the upper left to "no wrap (head)".
For the second issue, you are using:
ratingMsg[score]
but, your array is a sparse array not guaranteed to have an entry for most possible scores. You simply can't do it that way because many elements you access will have undefined values which won't give you a meaningful message. For example, if score was 15, you would be accessing ratingMsg[15], but there is no value in that space in the array so you won't get a meaningful rating message.
The solution is to find a different way to select the right message. The simplest way would just be an if/else if/else if statement that would check which range the score is in and set the appropriate msg. There are more elegant table driven ways, but all will involve searching through a data structure to find which two values the current score is between and using that msg.
If you look at this jsFiddle http://jsfiddle.net/jfriend00/dA7XC/, you'll see that your code is getting called, but it only hits values in the array sometimes.
And, here's a rewritten algorithm that finds the appropriate msg no matter what the score show in this fiddle: http://jsfiddle.net/jfriend00/jYcBT/.
It uses a data structure like this:
var ratingMsg = [
0, "Unclassified",
10, "Weak",
20, "Fair",
50, "Better",
60, "Medium",
70, "Good",
90, "Strong"
];
and a for loop like this to get the appropraite ratingMsg:
for (var i = ratingMsg.length - 2 ; i >= 0; i-=2) {
if (score >= ratingMsg[i]) {
msg = ratingMsg[i+1];
break;
}
}
Here you go: http://jsfiddle.net/RSq4L/11/
The first problem is that in your fiddle you have the onLoad option set, so your passwordStrength function is not actually being declared in the global scope. It is being declared inside of the onLoad block that jsFiddle wraps your code with. This causes the page to error out when the keypress handler tries to invoke the function.
You can fix this problem in several different ways:
By explicitly declaring the function as global as per my example above.
By choosing one of jsFiddle's "no wrap" options instead of onLoad.
By dynamically binding your event-handler instead of setting it through the element's onkeydown attribute in the markup.
The second problem is how you are keying your score messages. You have:
var ratingMsg = new Array(0);
ratingMsg[0] = "Unclassified";
ratingMsg[10] = "Weak";
ratingMsg[30] = "Fair";
ratingMsg[50] = "Better";
ratingMsg[60] = "Medium";
ratingMsg[70] = "Good";
ratingMsg[90] = "Strong";
...and you lookup the message by doing ratingMsg[score]. This will only work if the score exactly matches one of your indices. And based upon your math this will not always be the case.
I would suggest doing something like:
ratingMsg = {};
ratingMsg[0] = "Unclassified";
ratingMsg[10] = "Weak";
ratingMsg[30] = "Fair";
ratingMsg[50] = "Better";
ratingMsg[60] = "Medium";
ratingMsg[70] = "Good";
ratingMsg[90] = "Strong";
function closestRating(score) {
var bestKey = 0;
var bestMatch = 100;
for (var key in ratingMsg) {
if (key <= score && score - key < bestMatch) {
bestMatch = score - key;
bestKey = key;
}
}
return ratingMsg[bestKey];
}
On an unrelated note, are you sure you want to be using onkeydown? I think onkeyup would work better.
Your fiddler script had several errors. Here's the corrected one: new script.
You were missing a semicolon here: document.getElementById("passwordDescription").innerHTML = "" + ratingMsg[score] + ""
You forgot to escape '^' on your regular expression
I just wrote this for it:
Jquery Plugin for password strength forcing

Mind boggling javascript failure at handling some basic addition!

This is killing me! I'm trying to add the values of four fields together, and I get allllll kinds of wierd results!
The code I have so far:
$('input.percent').change(function() {
var totalup = 1;
var totalup = totalup*1;
$('input.percent').each(function(){
var current = $(this).val();
var curvalue = current * 1;
console.log(curvalue);
console.log(totalup);
var totalup = curvalue + totalup;
});
});
This should be ungodly simply. Start with a value of zero, get the value of each input, add it to that totaling value. The console log always shows UNDECLARED or NaN for totalup, but if I remove the last decleration of totalup (where it adds more to totalup) it suddenly doesn't become undefined or Nan.
Why is this not ungodly simply!!! I must be missing something dumb, or Javascript just STINKS!
Thanks in advance for your help!
var percentInputs = $('input.percent');
percentInputs.change(function() {
var total = 0;
percentInputs.each(function(){
total += Number($(this).val());
});
});
Update
Caching those selectors would be a good idea too.
the main problem is the declaration of already declared fields. Leaf the var keyword for the second and third assignment of totalup and it'll work.
add the parseInt() while the calculation for an example
var totalup = parseInt(curvalue) + parseInt(totalup);
Okay! Here is where the issue was arising!!!!
When you write:
var FOO = 'whatever';
...Inside of a function, it is a LOCAL VARIABLE! If however you simply go:
FOO = 'whatever';
You hit the global variable (variable declared outside of the function).
So while the code above is the solution, this is where the explained solution to the problem exists!

Categories