So, three small parts:
1) a MaxMind geo IP lookup that gets us the country code via the IP address:
var onSuccess = function(x){
var ip = x.traits.ip_address;
document.getElementById('ip_address').value = ip;
var country_code = x.country.iso_code;
document.getElementById('ip_country_code').value = country_code;
…
};
2) an array of country references with tax percent decimals:
// Array of values for tax rates
var tax_rates= new Array();
tax_rates["noteu"]=0.0;
tax_rates["ES"]=21.0;
tax_rates["AU"]=20.5;
tax_rates["BE"]=21.7;
…
3) a TaxPrice function that takes one of those decimals to calculating tax and then total payable in a subscription form. Notice the XXXXX:
function TaxPrice()
{
var taxprice=0;
XXXXX
return taxprice;
}
The document.getElementById bit in 1) can obviously update a hidden field or some other HTML element.
I know what to do with XXXXX if it's a manual drop down the user has to select.
But how do I get the tax decimal out of the array and into the TaxPrice function based on the IP address country code? (i.e. within the javascript, not updating an HTML element).
Happy New Year to all.
UPDATE: Just to be clear, I don't need to know how to get it into a drop down, I can do that already and in this use case, the user should not be allowed to choose his own tax country, it should be set automatically based on the IP address. So the non-code wording would go something like:
taxprice EQUALS tax_rate.value ACCORDING TO ip_address_code
Are you looking for something like element properties?
Mydiv.tax=taxvalue;
Properties of Elements are an elegant way of communicating between different functions.
You can assign any value to any element.
You can retrieve the value from any function in JavaScript as long as the Basic element lives.
One way you can do it is to set a global selectedCountryCode variable inside your success callback, and reference tax_rates[selectedCountryCode] in your TaxPrice array (which should be an object, as nnnnnn pointed out)
(function () {
var selectedCountryCode = "";
var onSuccess = function(x) {
var ip = x.traits.ip_address;
document.getElementById('ip_address').value = ip;
selectedCountryCode = x.country.iso_code; // <-- Set selectedCountryCode for later use
document.getElementById('ip_country_code').value = selectedCountryCode; // <-- Set dropdown value
};
document.getElementById("ip_country_code").addEventListener("change", function() {
selectedCountryCode = this.value;
console.log(TaxPrice());
});
// Object of values for tax rates
var tax_rates = {};
tax_rates["noteu"] = 0.0;
tax_rates["ES"] = 21.0;
tax_rates["AU"] = 20.5;
tax_rates["BE"] = 21.7;
function TaxPrice() {
var taxprice = 0;
taxprice = tax_rates[selectedCountryCode];
return taxprice;
}
})();
Change Me: <select id="ip_country_code">
<option value="noteu">noteu</option>
<option value="ES">ES</option>
<option value="AU">AU</option>
<option value="BE">BE</option>
</select>
So, thanks for your suggestions. Not sure if I understand how this is working exactly, but after some poking around, it now is. Compared to the code in the original question, I had to:
1) Add a global variable at the top, above everything else, unrelated to the IP lookup code (i.e. there is now no reference to country_tax within the IP onSuccess variable):
var country_tax;
2) Replace XXXXX in the TaxPrice function with:
var country_tax = document.getElementById("ip_country_code").value;
var taxprice = taxes_from_database[country_tax];
So the full TaxPrice function ends up as:
function TaxPrice()
{
var taxprice = 0;
var country_tax = document.getElementById("ip_country_code").value;
var taxprice = tax_rates[country_tax];
return taxprice;
}
No need, it seems, for nested functions or closures or anything very complicated. It doesn't matter (to the code) if the tax_rates are set up as an array or an object, the outcome is the same, although I would like to understand why you recommend an object over an array in this case.
And—given TaxPrice gets the value from the form field and not from within the IP onSuccess function—I don't know why I need the global variable declaration at the top, if anyone wants to have a go at explaining that…
Related
So, I have this function that, after an update, deletes elements from a table. The function, lets call it foo(), takes in one parameter.
foo(obj);
This object obj, has a subfield within called messages of type Array. So, it would appear something like this:
obj.messages = [...];
Additionally, inside of obj.messages, each element contains an object that has another subfield called id. So, this looks something like:
obj.messages = [{to:"You",from:"Me",id:"QWERTY12345.v1"}, ...];
Now, in addition to the parameter, I have a live table that is also being referenced by the function foo. It uses a dataTable element that I called oTable. I then grab the rows of oTable and copy them into an Array called theCurrentTable.
var theCurrentTable = oTable.$('tr').slice(0);
Now, where it gets tricky, is when I look into the Array theCurrentTable, I returned values appear like this.
theCurrentTable = ["tr#messagesTable-item-QWERTY12345_v1", ...];
The loop below shows how I tried to show the problem. While it works (seemingly), the function itself can have over 1000 messages, and this is an extremely costly function. All it is doing is checking to see if the current displayed table has the elements given in the parameter, and if not a particular element, delete it. How can I better write this function?
var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
for(var idx = 0; idx < theCurrentTable.length; idx++){ // through display
var displayID = theCurrentTable[idx].id.replace('messagesTable-item-','').replace('_','.');
var deletionPending = true;
for(var x = 0; x < theReceivedMessages.length; x++){
var messageID = theReceivedMessages[x].id;
if(diplayID == messageID){
console.log(displayID+' is safe...');
deletionPending = false;
}
}
if(deletionPending){
oTable.fnDeleteRow(idx);
}
}
I think I understand your problem. Your <tr> elements have an id that should match an item id within your messages.
First you should extract the message id values you need from the obj parameter
var ids = obj.messages.map(function (m) { return '#messagesTable-item-' + m.id; });
This will give you all the rows ids you need to keep and then join the array together to use jQuery to select the rows you don't want and remove them.
$('tr').not(ids.join(',')).remove();
Note: The Array.prototype.map() function is only supported from IE9 so you may need to use jQuery.map().
You could create a Set of the message ID values you have, so you can later detect if a given ID is in this Set in constant time.
Here is how that would look:
var theCurrentTable = oTable.$('tr').slice(0);
var theReceivedMessages = obj.messages.slice(0);
// Pre-processing: create a set of message id values:
var ids = new Set(theReceivedMessages.map( msg => msg.id ));
theCurrentTable.forEach(function (row, idx) { // through display
var displayID = row.id.replace('messagesTable-item-','').replace('_','.');
// Now you can skip the inner loop and just test whether the Set has the ID:
if(!ids.has(displayId)) {
oTable.fnDeleteRow(idx);
}
});
So now the time complexity is not any more O(n.m) -- where n is number of messages, and m the number of table rows -- but O(n+m), which for large values of n and m can make quite a difference.
Notes:
If theCurrentTable is not a true Array, then you might need to use a for loop like you did, or else use Array.from(theCurrentTable, function ...)
Secondly, the implementation of oTable.fnDeleteRow might be that you need to delete the last rows first, so that idx still points to the original row number. In that case you should reverse the loop, starting from the end.
I'm trying to return a value in acrobat depending on two other fields - one text and one a value.
Users select from a drop down box the frequency in box F1, I then need to turn this text into a number to then multiply by another box (X1) , depending on the text selected in F1.
So far I have attempted this but can't get the result I would expect. Your assistance would be appreciated, I've very new to javascript! Many thanks.
var frequency_values= new Array();
frequency_value["Monthly"]=12;
frequency_value["Quarterly"]=4;
frequency_value["Semi-annually"]=2;
frequency_value["Annually"]=1;
document.getElementById("F1").value = frequency_value;
g.value = this.getField('frequency_value');
h.value = this.getField("X1");
event.value = (h.value * g.value)/52;
Try this:
function getField(f) {
// not sure what getField does in your app, but i'm just defining it here and return a number for debugging in console
return 20;
}
var frequencyValues = {
'Monthly': 12,
'Quarterly': 4,
'Semi-annually': 2,
'Annually': 1
};
// lets get the user selection form the select drop down
// var f1 = document.getElementById('F1').value;
var f1 = 'Monthly'; // for debugging in our console, lets just set it to monthly
// not sure what g and h are, but we'll just define them here
var g = {},
h = {};
g.value = frequencyValues[f1];
h.value = this.getField('X1');
var value = (h.value * g.value) / 52;
console.log(value);
The idea is to create an object named frequencyValues, not array.
And when you access it, you access it using obj[field].
Since I don't have your code, so I created the getField function and commented our the document.getElementById, but I think you get the idea.
BTW, not sure what your language background is, but try to stick to camel standard you code Javascript, ie. frequencyValues instead of frequency_values. Try to avoid underscore in variables and function names at all costs.
Good luck.
I am using the SharePoint JavaScript Object Model within an Angular controller to retrieve data from the Taxonomy (term store). By using $scope.apply, I am able to bind the array to scope and use the values in a dropdown since SharePoint's JavaScript Object Model is not a normal Angular function understood by scope. This works as intended.
Now I need to set the value of the field to the current value stored in the database. This works with the following for dropdown/choice based fields where I retrieve the index of the item via a search of the array. Example:
var currentCategoryIndex = $scope.categoryValues.map(function (e) { return e.value; }).indexOf(currentCategoryValue);
$scope.vm.selectedCategory = $scope.categoryValues[currentCategoryIndex];
However, I can't access my array within the controller to check for the index (see code below). It does, however, bind the $scope for use in the dropdown via the $scope.$apply.
Something else really odd is if I add an alert, it will start working, like it somehow forces scope back. But using an alert on page load every time just to get the array working is not realistic.
I need to access the array so I can compare against it and get the index so I can set the field value to the correct item currently stored in the database.
Here is the function in my controller. Note that I need to run a sub function to get all the values. This works to create the $scope.termsArray binding that I use in my dropdown, it is the setting of $scope.vm.selectedCategory where the issue is occurring:
var termsArray = [];
// Query Term Store and get terms for use in Managed Metadata picker stored in an array named "termsArray".
function execOperation() {
// Current Context
var context = SP.ClientContext.get_current();
// Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
// Term Stores
var termStores = taxSession.get_termStores();
// Name of the Term Store from which to get the Terms. Note, that if you receive the following error "Specified argument was out of the range of valid values. Parameter name: index", you may need to check the term store name under Term Store Management to ensure it was not changed by Microsoft
var termStore = termStores.getByName("Taxonomy1234");
// GUID of Term Set from which to get the Terms
var termSet = termStore.getTermSet("1234");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
var termEnumerator = terms.getEnumerator();
while (termEnumerator.moveNext()) {
var currentTerm = termEnumerator.get_current();
var guid = currentTerm.get_id();
var guidString = guid.toString();
var termLabel = currentTerm.get_name();
// Get labels (synonyms) for each term and push values to array
getLabels(guid, guidString, termLabel);
}
// Set $scope to terms array
$scope.$apply(function () {
$scope.termsArray = termsArray;
console.log($scope.termsArray); // DOES NOT LOG ARRAY
});
var currentFacilityIndex = termsArray.map(function (e) { return e.termGUID; }).indexOf(currentFacilityGUID);
console.log(currentFacilityIndex);
$scope.term.selected = termsArray[currentFacilityIndex];
}, function (sender, args) {
console.log(args.get_message());
});
// Get labels (synonyms) for each term and push values to array
function getLabels(termguid, guidString, termLabel) {
var clientContext = SP.ClientContext.get_current();
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(clientContext);
var termStores = taxSession.get_termStores();
// The name of the term store. Note, that if you receive the following error "Specified argument was out of the range of valid values. Parameter name: index", you may need to check the term store name under Term Store Management to ensure it was not changed by Microsoft
var termStore = termStores.getByName("Taxonomy1234");
// GUID of Term Set from which to get the Terms
var termSet = termStore.getTermSet("1234");
var term = termSet.getTerm(termguid);
var labelColl = term.getAllLabels(1033);
clientContext.load(labelColl);
clientContext.executeQueryAsync(function () {
var labelEnumerator = labelColl.getEnumerator();
var synonyms = "";
while (labelEnumerator.moveNext()) {
var label = labelEnumerator.get_current();
var value = label.get_value();
synonyms += value + " | ";
}
termsArray.push({
termName: termLabel,
termGUID: guidString,
termSynonyms: synonyms
});
}, function (sender, args) {
console.log(args.get_message());
});
}
};
// Execute function
execOperation();
UPDATE: I tried setting the $scope.termsArray = []; per the suggestion below, but it didn't work. What is really odd is that if I have an alert as follows, it somehow forces the console to log/grants me access to the array in the controller.
$scope.$apply(function () {
$scope.termsArray = termsArray;
alert("hey");
console.log($scope.termsArray);
});
I found a bit hard to follow your code.
My first guess would be to instantiate the array with empty value before anything else.
$scope.termsArray = [];
This trick tells Angular that this property exists and will exist at later stage.
I am experementing with javascript objects for the first time and need some help. I want to store generated user input in objects, push them into an array and later on reuse them. So far I have come to this:
function changeColors() {
//get the numbers from the html
var rd = parseInt(document.getElementById("red").value);
var gr = parseInt(document.getElementById("green").value);
var bl = parseInt(document.getElementById("blue").value);
var op = parseFloat(document.getElementById("opacity").value);
//convert the decimal into hexadecimal
var rdhex = (rd < 16) ? "0" + rd.toString(16) : rd.toString(16);
var grhex = (gr < 16) ? "0" + gr.toString(16) : gr.toString(16);
var blhex = (bl < 16) ? "0" + bl.toString(16) : bl.toString(16);
//concatenate all hex to generate a color
var hexcode = "#" + rdhex + grhex + blhex;
//view the change in the browser
document.getElementById("div").style.backgroundColor = hexcode;
document.getElementById("colordisplay").innerHTML = hexcode;
//change opacity
document.getElementById("div").style.opacity = op;
Here I get all the input that I need to store and in the next function I am trying to store it in an object and array:
function Save(){
var colors = {};
var nextColor = []
colors.nextColor = nextColor;
console.log(colors);
var rgb = document.getElementById("colordisplay").innerHTML;
var opacity = document.getElementById("div").style.opacity;
var name = document.getElementById("name").value;
var nextColor = {
"name": name,
"rgb": rgb,
"opacity": opacity
}
colors.nextColor.push(nextColor);
console.log(colors);
}
My question is: is how wrong is that and how it can be corrected?
Thank you!
I am unsure what your question exactly is, but looking at your code for Save I assume you're inquiring how to best store data in the context of an application. Looking at the Save-method body:
var colors = {};
var nextColor = [];
These variables are only available in the scope of the Save function. As such the "colors"-Object will only ever contain one single color Object, i.e. the "nextColor" Object created in the Save function. On top of this, the "colors"-Object is not accessible outside of the Save function, rendering it... well, useless.
Ideally you hold the contents of the "colors"-Object in a global variable (or reference it in another Object available to your application, i.e. a "Model") and fill the colors Object with the return of the Save-method, i.e.:
function Save() {
var rgb = document.getElementById("colordisplay").innerHTML;
var opacity = document.getElementById("div").style.opacity;
var name = document.getElementById("name").value;
var nextColor = {
"name": name,
"rgb": rgb,
"opacity": opacity
};
return nextColor;
}
// assume an event handler invoked after a form is submitted, this
// creates a nextColor and pushes it into the existing colors Object
function someEventHandler( e ) {
colors.nextColor.push( Save() );
}
This implies that the Save-methods sole function is to gather the values entered in the HTML document, and translate it into a new value Object. The Save-method now has no business knowing about any remaining data belonging to your application. (i.e. the creation of the "colors" Object and its "nextColor"-Array should be left to another function, ideally executed when your application launches).
I guess what I'm saying is you're on the right track, but you can get a lot of mileage by investing some time into creating separate functions to handle your data layer. After all, that's all JSON is, data.
If for instance you want to enter validation in your Save()-method (let's say to make sure that the "name" Input element actually contains a valid String), you just modify it there in that one function. If you additionally wish to make sure that the same color isn't added to the "nextColor"-Array twice, you can make another function that checks whether a color with the same values is already present in the data Object and either removes it or prevents pushing the duplicate value into the Array. This is logic that shouldn't be in the Save()-method, as such you can structure your program to organize your data neatly.
I hope this is the answer you were looking for.
Try this:
var colors = {
"nextColor": []
};
function Save() {
colors.nextColor.push({
"name": document.getElementById("name").value,
"rgb": document.getElementById("colordisplay").innerHTML,
"opacity": document.getElementById("div").style.opacity
});
console.log(colors);
}
Notice that the colors variable should be outside the scope of the function in order to retain the variable beyond individual runs of the Save() function.
I've also simplified the code quite a bit.
This is annoying me.
I'm setting an array in beginning of the doc:
var idPartner;
var myar = new Array();
myar[0] = "http://example.com/"+idPartner;
And I'm getting a number over the address, which is the id of partner. Great. But I'm trying to set it without success:
$.address.change(function(event) {
idPartner = 3;
alert(idPartner);
}
Ok. The alert is giving me the right number, but isn't setting it.
What's wrong?
Changing the value of the variable does not re-set the values within the array. That is just something javascript can't do automatically. You would have to re-generate the array for it to have the new id. Could you add the id to the value where you use the array instead of pre-setting the values in the array containing the id?
Edit: For example, you would do:
var myArray = [];
var myId = 0;
myArray[0] = "http://foo.com/id/";
and when you need to use a value from the array, you would do this:
var theVal = myArray[0] + myId;
Try this:
var myvar = ["http://site.com/"];
$.address.change(function(event) {
myvar[1] = 3;
}
then use myvar.join () where you need the full url.
The problem here is that at the line
myar[0] = "http://site.com/"+idPartner;
..you perform a string concatenation, meaning you copy the resulting string into the array at index position 0.
Hence, when later setting idPartnerit won't have any effect on the previously copied string. To avoid such effect you can either always construct the string again when the idPartnervariable updates or you create an object and you evaluate it when you need it like...
var MyObject = function(){
this.idPartner = 0; //default value
};
MyObject.prototype.getUrl = function(){
return "http://site.com/" + this.idPartner;
};
In this way you could use it like
var myGlblUrlObj = new MyObject();
$.address.change(function(event){
myGlblUrlObj.idPartner = ... /setting it here
});
at some later point you can then always get the correct url using
myGlblUrlObj.getUrl();
Now obviously it depends on the complexity of your situation. Maybe the suggested array solution might work as well, although I prefer having it encapsulated somewhere in an object for better reusability.
myar[0] = "http://site.com/" + idPartner;
After this line, myar[0] = "http://site.com/undefined" and it has nothing to do with the variable idPartner no more.
So, after that changing the value of idPartner will affect the value of myar[0].
You need to change the value of myar[0] itself.