Here's the fiddle: http://jsfiddle.net/K5dsh/
I'm trying to make a simple calculator that evaluates the difference between the numbers its given, and gives an answer based on that. It has two problems:
1.) The answer my script gives is always the result of my 2nd else if statement, even if the input matches the conditions before it.
2.) The answer does not change even when there's a new input that should give a different result.
Does anyone see what the problems are? Thank you.
As Ivan pointed out, you're never updating the values of high, low and common with the values entered into the textboxes. You should be assigning the values inside the calculate function. See updated fiddle.
Also, you may want to invest some time into learning a framework like Knockout.js. It makes data-binding HTML form elements to JavaScript view models incredibly simple.
Your variables are defined only once. You should change it so that every time your button is clicked, it grabs the new variables. Here is an example: http://jsfiddle.net/Vd8n4/
Your values aren't being updated.
Here's how I would go about it. I'd change your function so that it starts off like this. That way, every time it is called, it updates the high, low, and common values.
function calculate() {
var high = document.getElementById('highRi').value;
var low = document.getElementById('lowRi').value;
var common = document.getElementById('comm').value;
Related
In Qualtrics, I am trying to set two embedded data fields based on the answer to a yes or no question by using an if/else statement in JavaScript. I tried to come up with the correct code, but I am new to JS and what I've come up with (shown below) isn't working; the fields don't get populated.
I have created the embedded data fields in the beginning of the survey flow, so I don't think that's the issue.
Qualtrics.SurveyEngine.addOnPageLoad(function() {
if("${q://QID14/ChoiceGroup/SelectedChoices}"!="Yes")
{Qualtrics.SurveyEngine.setEmbeddedData("Active_Duty_Yes", "X");
Qualtrics.SurveyEngine.setEmbeddedData("Active_Duty_No", "")}
else if("${q://QID14/ChoiceGroup/SelectedChoices}"!="No")
{Qualtrics.SurveyEngine.setEmbeddedData("Active_Duty_No", "X");
Qualtrics.SurveyEngine.setEmbeddedData("Active_Duty_Yes", "")};
});
Your onload function name is wrong. It should be addOnload instead of addOnPageLoad.
A couple of other suggestions:
Is is generally better to use use recodes instead of strings in
logic (e.g., "${q://QID14/SelectedChoicesRecode}"!="1"). That way
if you change the choice text the logic doesn't have to change.
It is generally better to give embedded data flags values of 1 and 0.
So i've been asked to remake some registration forms. The way its supposed to work is, that an interpreter chooses X amount of languages in the first select box. Then based on the selections of languages, the user must specify from which languages they can translate from/to.
I want to store this data in a key/value array, with the key being "LanguageFrom" and Value being another array, of "LanguagesTo". This is how i have solved this:
function btnTest() {
var fromArray = $('.freelancerLanguagesFrom').map(function() {
return $(this).val();
}).get();
var toArray = $('.freelancerLanguagesTo').map(function() {
return $(this).val();
}).get();
var tempArray = {};
tempArray[fromArray] = toArray;
}
This method is being called with an "onclick" function in the html part. The user should specify which languages he can translate to for each of the chosen languages in the first box,
I am aware that this probably isn't the ideal approach, but im still an inexperienced developer, and i'd love to hear your take on another approach.
Now comes my problem:
1) How do i make it so the array wont overwrite the existing array with each button click, and instead just add to the array?
2) How do i process this array on the server side (php), so that i can store the values in my database?
3) Is it possible to skip the flow where the user has to press the save(gem) button after each language he has chosen?
edit: Question 1 and 3 are now solved, my only problem is accessing the array i made in js, on the php side
1) tempArray exists only in the scope of the btnTest() function. Declare it outside (in the global scope), initialize it as {} and don't reset it every time you click the button. The way you get the fromArray variable may require some tweaking depending on whether the "from" list can accept a multiple selection or not.
2) Ajax may help. Create a php endpoint to receive the request and call it using ajax. You can work on the array using JSON. Send your data using JSON.stringify(tempArray) and read it using json_decode() in your php script, or simply set the request headers as "application/json" to have it done automatically for you.
3) I personally wouldn't automate this process. Let's say I have 4 languages, Italian, English, French and Chinese.
I have selected a desirable state of languages I can handle:
Italian -> English, French
But I also know how to translate French in Italian so I click, in the from list, French, and I get
French -> English
Which is an undesirable state, for me, because I don't know how to do that. Especially if I were to select many languages, I'd get, inbetween 2 states I want to save, an indefinite amount of states I don't want to save.
If you still want to do so, you need to move the even listener from the button to the list(s), with the onchange event.
I'd also suggest you do your event binding trough jQuery, if you aren't already.
Hope this helped.
Since I'm new to JavaScript, I should work on a small Calculator.
I managed to get the easy things like plus and minus,.. done, now I was trying to get myself some thoughts about getting a squareroot into it.
It is like, I have got 3 drop down - select lists. The first one is for the first number, the second one is for the symbol of the calculation, and the third one is for the second number.
But if I want to get the squareroot into it, I only need one of the select lists, so I'd like to know, if there is a way to block one of the select lists in a JS function, since I only need to block it for the sqrt?
(I'm sorry if that isn't the best english =))
Do your part of the logic then use the following to enable/disable...
document.getElementById("mySelect").disabled = true;
document.getElementById("mySelect").disabled = false;
I think that's what you meant???
I've been wracking my brain over this for a few days, so I figured it's time to finally ask somebody who actually knows what they're doing. ;)
I'm building an AngularJS app and getting an odd behavior when I'm iterating through a couple of my for loops. I'm trying to find the 'best' option to add to a list given a few possibilities, and so here's my general process for how I'd like to get it done:
The Idea:
1) add each possibility to the desination list, say $scope.list1
2) calculate the 'score' based on the state of the lists
3) remove the possibility from $scope.list1
4) repeat for all possibilities.
Here's the basic idea of what I'm running in my controller:
$scope.getSuggestions = function(){
//for each possibility to consider:
for(var i = 0; i < possibilities.length; i++){
//add the possibility to the scope as per usual
$scope.list1.push(possibilities[i]);
//calculate the score given the state of the scope
$scope.calculateScore();
//save the score in a new object on the scope
$scope.results.push({"option": possibilities[i],
"score": $scope.score
});
//remove the possibility to reset the scope back to its original state
$scope.list1.pop();
}
};
The Problem:
It seems as if my for loop is actually moving on to further iterations before the code has finished executing. My $scope.calculateScore() function may take a bit of time to run, and it seems like it's being ignored by the for loop. I'm not doing anything obviously asynchronous in that function; it's mostly other for loops based on the state of the $scope and some math to get a 'score'.
My question:
Why does Angular think it's okay to continue blazing through a for loop when the code inside hasn't finished executing? I see how it could make sense in certain cases, but in this one it's vital that everything happens in order, after the previous functions have finished. Do you all have any suggestions on how to make this work?
Note: You can see the code in its entirety by viewing the source at http://www.PlatTheLeague.com
The actual code for calculateScore() is in scripts/controllers/teamBuilderCtrl.js, where the function is called $scope.populateGamePredictions(). My initial tries at the suggestions are in the same file, called $scope.getChampSuggestions. To see the problem, drag an item from the list on the left to the box that says 'Their Top' and then click on the 'Champion Suggestions' tab. That tab should be populated with the results of $scope.results listed above in the pseudo-code, but it seems that the teamScore on my scope object isn't being set properly.
Cheers!
Maybe you have some logics that change the internal states of $scope from outside of AngularJS, maybe from some kinds of events from DOM, ajax callbacks, setTimeout ... In that case, $apply method can help. You can have more references of $apply from here: https://github.com/angular/angular.js/wiki/When-to-use-$scope.$apply()
As it turns out, The above idea works in the typical synchronous manner, as I've proved to myself in this plunker: http://plnkr.co/edit/9spVbf5JWx9Hnq53sHSV?p=preview
My issue arose from the fact that the data model being worked on by my calculateScore() function was not formatted exactly how I thought it would be (my own fault, thanks to the semi-complicated nature of the app...) which meant that the scores weren't being updated properly in the first place, though the code was running as expected.
I am trying to build simple shopping cart where the user input books information and price, the javascript file would validate the input then after inputting several books info, the user would be able to view the order with books details and total price. The problem is that even if there was an error with the dataentry, the wrong information would be stored and hence I get a NaN for the total price.
In function Validate() you start off with var correct = 'true' and later have an if statement checking if it is still true, however there is no code before that if which could possibly change var correct to a value other than true. I'm guessing you forgot to add correct = 'false' in each of the ifs you have checking the variables.
Also, if you want var correct to be a boolean rather than a string, get rid of the "" around true.
var Price=document.getElementById('Price').value;
if(isNaN(Price)||Price="")
{alert("Please enter numbers only for price");
correct = false;
}
It's never a good idea to perform client side navigation. What if someone has javascript disabled? (Blackberry phones). They will pass your validation, and boom, everything messes up.
As for your question, it would be easier to answer if you could have an isolated test case in a fiddle.
EDIT: As others said, it's simply because you aren't doing correct = false every time in the if statements.