I'm looking for a way to get all the information out of localStorage. The trouble I'm having is I don't know what the data will be as it is user generated.
So here what happens, a user inputs some text, it uses javascript to manipulate it depending on what check boxes they have ticked on the input form. these boxes are for symbols for example if they tick the box for # then the text + the #At (symbol then word) will be placed in local storage with the other half of the pair as a Boolean (1 or 0 in this case) representing whether its been checked.
the exact pair would look like this:
someString..#At | 1
someString..#Hash | 0
etc.
It should also be noted that this is intended to be used in a Chrome Extension so compatibility in other browsers is not a requirement for me (although it could well be usful to others reading this as I can't find anything else covering it on the web).
So, if there anyway I can extract all the values in localStorage without actually knowing the name of each key?
Is it possible to use any kind of wild card or regular expression maybe, I have tried this but should make it work using a for loop.
Thanks,
Wez
window.localStorage.key is the solution.
Example:
var i = 0,
oJson = {},
sKey;
for (; sKey = window.localStorage.key(i); i++) {
oJson[sKey] = window.localStorage.getItem(sKey);
}
console.log(oJson);
Related
I have a bunch of dropdownlists that are filled dynamically with Jquery but i'm trying to convert them to Asp:DropDownLists instead of actual pure HTML select dropdowns so i can access and manipulate their values directly from the server side more easily (so i can save the Session value) instead of having to use the Request.Form command. Since the Asp:DropDownList class has it's particularities, i had to adapt the code i had including the Javascript/Jquery functions which access the drops and fill them (all of their ids share a similar nomenclature but with a different number at the end). However, when i try to access the ID, this doesn't seem to work:
$('#<%= select_plan_'+i+'.ClientID %>')
I always seem to get this compilation error:
CS1026: ) expected
The "i" has to be there since i'm using a "for" loop to go through all of the drops and fill them. Like i mentioned, all of the drops's ids share a similar nomenclature but with a different number at the end.
This is how one of the drops is defined:
<asp:DropDownList runat=server id="select_plan_4" onchange=ChangePrice(this,4);SetSelectedText(4); name=select_plan_4>
...
</asp:DropDownList>
Anyway, how can i get over this issue? Is there a better alternative? Thanks in advance!
UPDATE: Js function code added.
function ChangePlan(n, control) {
family = decodeURIComponent(window.location.search).split('=')[1];
$('#select_plan_'+n).find('option').remove().end();
for (var i = 1; i < data.length-1; i++) {
var aux = data[i].split(';');
if (aux[0] == family) {
var html='<asp:ListItem Value="'+aux[control]+'" Text="'+aux[1]+'" >'+ aux[1] +'</asp:ListItem>';
$('#select_plan_'+n).append(html);
}
}
}
Have a look at the rendered HTML of your page in the Dev Tools for your browser (e.g. by pressing F12 when using Chrome). You'll see that usually the controls, when they're actually rendered, don't have the IDs you've assigned them.
You need to find the actual ID of the rendered control. For a good description of a few techniques for doing this, check out this blog post.
I want to extract out the query string values from the URL.
So, in the most upvoted answer in How can I get query string values in JavaScript? - window.location.search is used.
Is there any problem in using window.location.href?
I am trying to root cause a problem where in sometimes I am getting empty query string value when using location.href
The 2 properties return different things:
href: Is a DOMString containing the whole URL.
and:
search: Is a DOMString containing a '?' followed by the parameters of
the URL. Also known as "querystring"
So you could use one or the other, just make sure to account for the differences between the returned values in your function. If you decide to use the href property you will need to first extract the query string part (the part after the ?) before splitting it into pieces.
Browsers now have a URLSearchParams class that can help to parse search params. It has been around in modern browsers for almost 4 years now: https://caniuse.com/?search=URLSearchParams
let queryParams = new URLSearchParams(window.location.search)
queryParams.set('page', '1')
queryParams.toString()
queryParams.get('page')
queryParams.delete('page')
i use
var qr={};
window.location.search.substring(1).split("&").forEach(p => { qr[p.split("=")[0]] = p.split("=")[1] })
//use
console.log(qr["sample"]);
//or
console.log(qr.sample);
Note - if there is not location.href.search value you will get a null string.
You can explore the DOM of a page - any page - using a browser's Inspect feature to look at values.
You can learn a lot about the DOM using this procedure - more than most every even hear about.
Open the inspector (how depends on the browser but try right clicking anywhere on the page and check the drop down menu that you'll see - it may read Inspect or Inspect Object.
Once the inspector is open, click on console in the menu at the top of the inspector frame.
For Foxfire, the input line, where you can type in things to explore the DOM is at the bottom of the inspector window and is prefixed with >>
Note - Chrome shows you a multi-line input field, Firefox only a one line field. If you have Chrome - use it to inspect things, after you type something and press Enter the value you want will be displayed under what you type and the cursor moved down to the next blank line so you can enter something else.
Firefox allows you to view things but it clunky and a tad harder to use.
Into the input line or field, type:
document.location.
A list of all the properties for the location of the document (the URL) will be displayed and it has auto fill in to help you.
For example:
document.location.search will show any text in the URL following the # sign in the URL
document.location.href will show the you the entire URL
document.location.host will show you the host part of the URL
Experiment and look at all the properties listed for document.location and you'll learn quite about bit about the document.location. property.
You can also type window. and see a list of the window object's property - one of which will be document.
Instead of typing document.location.href you could make it harder to type by typing window.document.location.href
They produce the same results because the top property is always assumed to be window.
For Firefox - After you type something and hit enter, the results will be displayed above the input line. To bring up what you last typed, so you can change it, press the up arrow key wile the cursor is in the input line.
With Chrome - as I said above, when you press enter, the value will be displayed the line you just typed and the cursor will be moved down to the next blank line where you can enter the name of another property to see what it's value is.
Explore top. and self. - you'll find the are the top window object (if there are multi-frames on the page - frames, not iframes) and the current window.
Spending some time exploring the properties of window. self. top. will teach you a lot about the DOM (Document Object Model) that you might not ever come across.
If you don't seen an input field or line, make sure you click Console in the inspector top menu.
If you decided to use, say, document.location.href you will code it like that in your JavaScript to get the value or to set the value - you can change the href and have the browser go to another web page.
Note - one of the other answers said
"If you decide to use the href property you will need to first extract the query string part (the part after the ?) before splitting it into pieces"
You need not split anything off. Explore all of the properties of document.location and you'll see that you can get the hash, search, etc. already "split off" from the location string.
Hash is the value after a pound sign (#) in the URL
Search is the value after a question mark (?) in the URL
Here are some other things to look at:
document.links
document.links[0]
document.URL
document.body
Just browse through the DOM - you will learn a lot.
Am assuming you know javascript array and few method
Use the window.location.href
var url = 'site.com/seach?a=val0&b=val1'
split the '?'
var someArray = url.split('?');
The someArray looks like this ['site.com/seach', 'a=1000&b=c']
index 0 is the window.location and index 1 is queryString
var queryString = someArray[1];
Go futher a split '&' so u get a key=value
var keyValue = queryString.split('&');
keyVal looks like this ['a=val0', 'b=val1'];
Now lets get keys and values.
var keyArray=[], valArray=[];
Loop through the keyValue array and split '=' the update keyArray and valArray
for(var i = 0; i < keyValue.length; i++){
key = keyValue[i].split('=')[0];
val = keyValue[i].split('=')[1];
keyArray.push(key);
valArray.push(val);
}
Finally we have
keyArray = ['a', 'b'];
valArray = ['val0', 'val1'];
Our full codes looks like this.
var url = 'site.com/seach?a=val0&b=val1';
var someArray = url.split('?');
var queryString = someArray[1];
var keyValue = queryString.split('&');
var keyArray=[], valArray=[];
for(var i = 0; i < keyValue.length; i++){
key = keyValue[i].split('=')[0];
val = keyValue[i].split('=')[1];
keyArray.push(key);
valArray.push(val);
}
DONE!
I have this form, an official form (a character sheet for use at an Organized Play Event for a role-playing game, if it matters to anyone), that someone kindly turned into a fillable PDF form. I asked a question earlier about checkboxes and auto-calcualtions, and got that to work...but now I need to account for another variable (situational doubling of the Proficiency Bonus) in some of my calculations. Unfortunately, this variable is not represented anywhere on this form, and I can't just add fields to the form (it being an official form, at least when printed). Without adding more fields to the (printed) form, how can I account for this additional variable?
I thought about just allowing the user to override the auto-calculation by typing in the field, but I can't figure out how to make that happen. Is this a good solution? Is this relatively simple to code?
If your answer involves adding code to my form, please include a code snippet I can modify, and a description of where I should insert it into my existing code, or if there is somewhere else I need to be adding it instead.
Code Sample:
//check bonus = stat bonus + applicable proficiency bonus
var profUse = this.getField("SklAcrProf").value;
var stat = Number(this.getField("DEX1").value);
var profVal = Number(this.getField("Proficiency Bonus").value);
var check = Number('-2');
if (profUse != "Off"){
check = stat + profVal;
}
else{
check = stat;
}
event.value = check;
If the form only needs to remain the same, when printed, the simplest solution may be to go ahead and add the fields that you need. You can set them up, so that they are "visible but doesn't print". This option can be selected in the Form Field drop-down list, in the Text Field Properties, General Tab, under Common Properties.
This way, you can still incorporate the data in your formulas, but it has no affect on the printed document.
The professional edition licence of Salesforce does not allow the use of APEX code or Workflow unless purchased separately.
I have a requirement to clean up text in Salesforce that was input via on a web form that I do not control. The client wants to fix any text with ALL CAPS or missing sentence capitalisation.
I've seen this answer on a this question Is it possible to add style to a field in Salesforce? which uses javascript within a custom side bar component . It assumes that the transformation is to occur as the user types the data into the application. My requirement might allow for a custom salesforce button to invoke the action on the fields as the data will populated by an automated process.
Assuming I were to follow the same pattern I would have to find a way to reliably detect and fix bad formatting within a string.
Is there a good way to do this with javascript within salesforce?
I have found a way to get closer to what I need thanks to a regular expression and the AJAX toolkit.
I have created a custom detail button that invokes javascript OnClick.
The code takes the current lead and searches the Description field for any strings of >2 characters that are uppercase, within the characther class [A-Z]. Each time it matches a string it will replace that string with a lowercase version of itself.
Once the string has been 'cleaned' the lead can be updated.
{!REQUIRESCRIPT("/soap/ajax/19.0/connection.js")} //adds the proper code for inclusion of AJAX toolkit
var url = parent.location.href; //string for the URL of the current page
var updateRecords = []; //array for holding records that this code will ultimately updated
var re = new RegExp('[A-Z]{2,}', 'g');
var inputString = "{!Lead.Description}";
var matches = inputString.match(re);
if(matches != null){
for(var i = 0; i< matches.length;i++){
inputString = inputString.replace(matches[i], matches[i].toLowerCase());
}
var update_Lead = new sforce.SObject("Lead"); //create a new sObject for storing updated record details
update_Lead.Id ="{!Lead.Id}"; //set the Id of the selected Lead record
update_Lead.Description = inputString;
updateRecords.push(update_Lead); //add the updated record to our array
}
result = sforce.connection.update(updateRecords); //push the updated records back to Salesforce
parent.location.href = url; //refresh the page
I based this code on some that I found Salesforce: Custom Button to Execute JavaScript
It should be possible to amend this code to work on any Salesforce object and to work over a selection of fields. The code that does the replacement could be moved into a function to make this easier.
I am trying to edit some existing JavaScript validation code.
Using the onkeydown event, the code checks that the value in a textbox does not go past a maximum length. I cannot use <input maxlength="value" /> as there may be some formatting characters in the string that I can safely exclude from the maximum length.
The code works fine apart from when the user has pressed the insert key to turn overtype on and they have reached the maximum length. When this occurs if they place the cursor before a character and try to overwrite it the validation thinks that this will go over the limit and doesn't realise that a character will actually be replaced.
This answer states that I cannot detect if overtype is on, but doesn't provide any references. So assuming that I cannot detect overtype, is there anyway in the onkeydown event to detect if a character is going to be replaced.
I am happy with an IE only solution.
Update: onblur is not appropriate as this will let them go many characters over the limit before warning them of the maximum length. I would like to prevent them from going over the limit.
Your handler should look at the entire value and check the length. If the length is legal, return. If not, you can update the value with a substring. You may have to use caret position to determine exactly how to manipulate the string which can be tricky as it's slightly different in IE and other browsers.
This is different from what you have now which is probably preventing keypress when max length is reached. Don't prevent keypress, just trim the resulting string.
I don't think your problem is with the onblur validation, but an event you calling on key press by the sounds of it (eg preventing the user to key any more once they reach the limit) or I have misunderstood.
IF your validation is indeed onblur, you shouldn't have to worry about things like insert/overwrite being enabled, you are only interested in what the value of the input element is once the user has completed their input.
IF you are trying to stop the user if they reach this limit as they type, I would write a function to compute the actual length you are testing. For eg,
function validateMyInput() {
var myInputField = document.getElementById('myInput');
var removeAllExcludedCharsResult = myInputField.value.replace('&','');//exclude &
var totalLength = removeAllExcludedCharsResult.length;
if(totalLength < 500) { //limit of this test is 500
return true;
}
else {
return false;
}
}
Obviously change this function to what you need and maybe make it more generic by passing in the element of the input, max length and array of excluded chars to make it reusable.
UPDATE
I have tested this problem is Chrome and the insert key seems to be ignored. IE on the other hand does overkey. However, it seems page specific, for eg, if i have enabled insert on Page A, it doesn't seem to affect Page B. I found this page which seems to be able to grab the keycode event even when insert has been pressed. It might be due to the following code?
if(window.event) {
event = window.event; //where event is the javascript key event.
}
Either way, the link above seems to have accounted for the problem, hopefully it will have the answer if the above is not correct.
Hope I haven't misunderstood what the problem was and this helped.