Basically what I am wanting to do is take the variable named FROM and swap it with the variable named TO and vice visa, the reason for this is to allow the user to press a button which swaps the variables over when pressed. Exactly how it does when you press the swap button on google translate. Below is the code for the variables ect, but I have no idea on how to code the button so they swap over so to speak.
function save_options_from() {
var select = document.getElementById("FROM");
var FROM = select.children[select.selectedIndex].value;
localStorage["default_currency"] = FROM;
var
}
function save_options_to() {
var select = document.getElementById("TO");
var TO = select.children[select.selectedIndex].value;
localStorage["default_currency_to"] = TO;
The FROM and TO variables are local to the two functions and don't exist at the same time. I think what you want is this:
var originalDefault = localStorage['default_currency'];
localStorage['default_currency'] = localStorage['default_currency_to'];
localStorage['default_currency_to'] = originalDefault;
I would suggest two hidden fields FROM_old and TO_old for doing the swapping, as you need to capture the value before you change it.
Related
I've looked through the prior questions but do not see an answer that I can understand (they are all more complicated than mine).
I'm bootstrapping some javascript using old manuals and my experiences using a scripting language back 15 years ago.
By modifying a tutorial file I have this code and it works fine
var oemdc1 = parseInt(document.getElementById("vehicle_oem_draw").value);
var oemdc2 = parseInt(document.getElementById("vehicle_added_draw").value);
var oemdc3 = parseInt(document.getElementById("new_vehicle_draw").value);
var oemdc4 = parseInt(document.getElementById("include_prism_draw").value);
var total_current_draw = document.getElementById("total_hourly_current_draw");
total_current_draw.value = oemdc1 + oemdc2 + oemdc3
But I need to add this code so that if the user clicks a radio button (include_prism_draw) they get a different total.
if (oemdc4 == 1)
total_current_draw.value = oemdc1 + oemdc2 + oemdc3 + prism_cd;
else
total_current_draw.value = oemdc1 + oemdc2 + oemdc3;
But I get the added value (prism_cd) in my calculation regardless of the radio button values (a "1" or a "0"). Even if neither button is clicked I still get the added value.
So I think I need some braces or parentheses or something.
I have the var prism_cd declared at the top of the doc and it is inserted into a results field so it is working in that sense.
Any help is much appreciated.
(Okay, found the edit link, they should make it more prominent).
I cut/pasted the code from #Adam and still get the prism_cd regardless of the state of the buttons. (prism_cd is a number I set as a var and it shows up accurately but even when I don't want it.)
the button code is below. Maybe there is a simple mistake
Include PRISM 1.5 mA current draw in calculation?
<input type="radio" name="include_prism_draw" id="include_prism_draw" value="1" /> Yes
<input type="radio" name="include_prism_draw" id="include_prism_draw" value="0" /> No
To answer the other question about the vars, they are from popups the user manipulates, the script adds the values from the popups and does so accurately until I add the yes/no code with the buttons.
If the user wants to add the prism current draw (prism_cd) they click yes and it is to be added but as I say it is getting added whenever the code is in the script. At this point I do not have either button set to be checked.
The rest of script works accurately as I can test with the spreadsheet I am porting it from.
I still have more things to work through but they are mostly based on this type of "if/else set a var" logic so once I get this working hopefully I should be good to go.
I very much appreciate the replies.
M./
I'm not certain what your problem is. But, the best practice for if..else syntax is to put both blocks in braces.
var oemdc1 = parseInt(document.getElementById("vehicle_oem_draw").value);
var oemdc2 = parseInt(document.getElementById("vehicle_added_draw").value);
var oemdc3 = parseInt(document.getElementById("new_vehicle_draw").value);
var oemdc4 = parseInt(document.getElementById("include_prism_draw").value);
var total_current_draw = document.getElementById("total_hourly_current_draw");
if (oemdc4 === 1){
total_current_draw.value = oemdc1 + oemdc2 + oemdc3 + prism_cd;
} else {
total_current_draw.value = oemdc1 + oemdc2 + oemdc3;
}
Look at this question: Get Radio Button Value with Javascript
You cannot get the value of a number of associated radio-buttons by just doing
document.getElementById(ID).value;
also look at this question, why you should not give the same id to multiple HTML elements: Why is it a bad thing to have multiple HTML elements with the same id attribute?
Now a possible simple solution for you problem (according to solution from first link):
You could write a function, which returns the value of your two radio-buttons:
function getPrismDrawValue()
{
// predefined result, if no radio button is checked.
// in this case result will be 0 -> "No"
var result = 0;
// get a list of all HTML-elements with the name 'include_prism_draw'
var radios = document.getElementsByName('include_prism_draw');
// loop through all this elements and check if one of them is checked
for (var i = 0; i < radios.length; i++)
{
if (radios[i].checked)
{
// get the value of the checked radio button
result = parseInt(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
return result;
}
Now your variable oemdc4 should be declared like this:
var oemdc4 = getPrismDrawValue();
EDIT to answer new question:
now your problem is here:
var oemdc4 = parseInt(document.getElementById("prism_draw").value);
if you pass 1.5 to parseInt()-function it will return 1.
use function parseFloat() instead to get your expected result.
var oemdc4 = parseFloat(document.getElementById("prism_draw").value);
I am using a JS library for facetracking/emotion detection called CLMtracker.
http://auduno.github.io/clmtrackr/examples/clm_emotiondetection.html
Note: Seems to work best in chrome for those trying to use it.
Is the example I am using, I am wondering how I can access the values for each emotion. For instance, I want check every 10 seconds what the values are and print to console. From this I would also like to compare the values to find the highest and find the emotion that is attached to that. I think I am right in saying that the max() function will give me the highest out of an array?
What I have tried:
I have tried to get emotionData[0].emotion and emotionData[0].value which should print Angry and the value, but it only prints 0. I have also tried the same method with data which does not seem to return anything.
EDIT
emotionData gets me:
however it does not seem to show any update/change as I make my expression change
ec.meanPredict(ctrack.getCurrentParameters()) returns an object containing all the current scores for all emotions.
To get the current score of "Angry", for example, you would do :
ec.meanPredict(ctrack.getCurrentParameters())[0].value
So, in order to get the current most probable emotion, you could do this :
function getCurrentEmotion()
{
if(!ec.meanPredict(ctrack.getCurrentParameters())){setTimeout(getCurrentEmotion,1000);return;}
var currentData = ec.meanPredict(ctrack.getCurrentParameters());
var currentScores = [];
//Gather all scores in an array
for(var i=0;i<currentData.length;i++)
{
currentScores.push(currentData[i].value);
}
//Get the biggest score
var max = Math.max.apply(null,currentScores);
//Calculate its index
var indexOfScore = currentScores.indexOf(max);
//Get the associated emotion
var emotion = currentData[indexOfScore].emotion;
console.log(emotion);
//Set up a loop (did not add 'var', to allow stopping it from outside)
currentEmotionLoop = setTimeout(getCurrentEmotion,3000);
}
To stop the loop at any time, do this :
clearTimeout(currentEmotionLoop);
By the way, the ec variable is declared privately, so in order for this to work, either remove var where it is declared :
var ec = new emotionClassifier();
or write this code in the same file, under the same scope.
When making a JavaScript script to iterate through a set of elements with the same class name, you can alter each of their properties individually.
How does the script know which element to edit if they don't have unique IDs? If they do in fact have unique ID's, how do you retrieve them? Using alert(); to display what is held in the node array from a simple document.getElementsByClassName(''); seems to display the type of element.
Could I actually store these results in an array for later use?
If on the documents load, I fetch an array of elements with a certain class name:
<script>
var buttonArray = document.getElementsByClassName('button');
</script>
Then iterate through this, and add the result at 'r' position to an object:
<script>
var buttonArray = document.getElementsByClassName('button');
var buttonObject = {};
for(r=0;r<buttonArray.length;r+=1)
{
buttonObject[buttonArray[r]] = [r*5,r*5,r*5];
}
</script>
Would I be able to find the array for each individual element with classname 'button' like so:
<script>
var buttonArray = document.getElementsByClassName('button');
var buttonObject = {};
function changeCol(buttonID)
{
var red = buttonObject[buttonID][0];
var green = buttonObject[buttonID][1];
var green = buttonObject[buttonID][2];
buttonID.style.backgroundColor = "rgb("+red+","+green+","+blue+")";
}
for(r=0;r<buttonArray.length;r+=1)
{
buttonObject[buttonArray[r]] = [r*5,r*5,r*5];
buttonArray[r].onclick = function(){ changeCol(this); };
}
</script>
I thought the this part of onclick = function(){ changeCol(this); }; would hold the same unique ID as I stored in the buttonObject object, as the variable name that held the array?
Should this work? I can't seem to get it to on my web page, so instead, I used the buttons innerHTML in the buttonObject as the variable name that held the array for that object. The problem with that, is that I will probably need two or more buttons to have the same innerHTML.
Here's the webpage as it currently is:
http://www.shadespeed.com
I need to re-make the script to allow buttons to have the same name.
Any tips / advice would be greatly appreciated.
Many thanks!
- Dan. :)
Let's say I have a deck of cards spread out on my desk, face up. I want to flip over all the red ones. I might do this:
desk.getCardsByColour("red").forEach(flipit);
// note, obviously not real JavaScript for a not real situation :p
So I scan through my cards, finding all the red ones. Then I flip them over. What you're asking is basically "how do I know which cards to flip over if they don't have unique IDs?" Well, do I need an ID to iterate through a collection of objects, in this case a set of cards? Of course not.
(Note that while cards in a deck do have a unique property in their content, let's just assume that's the element's content and not an id attribute, kay?)
Now, here's how I'd do what you're doing:
for( r=0; r<buttonArray.length; r++) {
buttonArray[r].buttonObject = [r*5,r*5,r*5];
buttonArray[r].onclick = changeCol;
}
function changeCol(button) {
var red = button.buttonObject[0];
var green = button.buttonObject[1];
var blue = button.buttonObject[2];
button.style.backgroundColor = "rgb("+red+","+green+","+blue+")";
}
This is a very basic question (I'm a novice in GAS and JS). I have the code bellow. When a use it, I'd like that the submit function returns the itemsSelected. But, since it's returning app, how can I acess itemsSelected values from submit function?
var fact_list = ["He planted a tree", "She visited a nursing home", "They have donated books to the library"];
function showList() {
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
var panel = app.createVerticalPanel().setId('panel');
// Store the number of items in the array (fact_list)
panel.add(app.createHidden('checkbox_total', fact_list.length));
// add 1 checkbox + 1 hidden field per item
for(var i = 0; i < fact_list.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(fact_list[i]);
var hidden = app.createHidden('checkbox_value_'+i, fact_list[i]);
panel.add(checkbox).add(hidden);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
app.add(panel);
mydoc.show(app);
}
function submit(e){
var numberOfItems = e.parameter.checkbox_total;
var itemsSelected = [];
// for each item, if it is checked / selected, add it to itemsSelected
for(var i = 0; i < numberOfItems; i++){
if(e.parameter['checkbox_isChecked_'+i] == 'true'){
itemsSelected.push(e.parameter['checkbox_value_'+i]);
}
}
var app = UiApp.getActiveApplication();
app.getElementById('panel').clear().add(app.createLabel(itemsSelected));
return app;
}
In your example the function submit(e) is a handler function called by the submit button, every value that you define in that function will not be available to any other function unless you create a second handler in this submit function with another event etc... (which is obviously not the case here).
So the only way to keep that value available to another function is to store it "somewhere" where it will be available for the other functions.
From there the choice is yours... You mentioned in the comment you don't wat to use scriptProperties, but you can use scriptDb or userProperties or even the spreadsheet in which you are working but it has to be somewhere and it can't be in the UI in the example you show unless you have another event in this UI that would call the third function we are talking about.
In this case (and only in this last case) you can use a hidden widget or an invisible textBox to assign a stringified value of your array and get it back in the handler using the classical e.parameter.varName but this doesn't seem to be your use case.
Hoping I'm being clear enough....
If not then feel free to mention it.
EDIT : just a note : You are using a Label to show the value of itemsSelected . That's not the best choice since Labels can't have names , meaning we can't get a value from them even if we had a handler and an event... Labels are definitely 'one way' to show values. If it where a textBox you could use some kind of handler to trigger another function and retrieve the itemsSelected value.
I'm working on a website with Jquery tabs dynamically generated. Each tab has an ID.
For the purpose of my script I need to know how many times the user has clicked in a tab.
To record the number of clicks I was thinking of doing an array like this:
var i = new Array(my_tab_id);
(...)
i[my_tab_id] = 0;
Where my_tab_id dynamically changes depending on the tab we're in. Sadly, it doesn't seem like the value of my_tab_id is translated into the array. I don't have i[5] = 0, i[6] = 0, etc. but rather i[my_tab_id], which doesn't help more than a simple var.
Any advice? Thanks!
In that case you shouldn't use an array, you should use an object, which you can treat like a hash.
var o = {};
var id = 'x';
o[id] = 1;
alert(o[id]);
This should allow you to store the click count onto each tab using the .data() function in jQuery each time a tab is clicked.
$('#example').bind('tabsselect', function(event, ui) {
var count = parseInt(ui.tab.data("clickCount"));
if (isNaN(count)) count = 0;
count++;
ui.tab.data("clickCount", count);
});
I think I understand your problem.
You are saying that the var i only has one element. This happens because the var i is newly instantiated every time you open a new tab. I'm guessing every tab is a new page or at least is a new context for var i.
If you want to keep an instance of an object (like an array) in between different pages, take a look at jStorage, it allows you to keep data locally on the browser and it makes it easier to maintain context between page loads.
If all tabs are on the same page then the solution is easier, you need to keep the array in a global variable for the page.
Are you sure my_tab_id is an integer when i[my_tab_id] = 0; is called?