Getting "Undefined" when using multiple Google Autocomplete - javascript

I have multiple forms that are using Google Autocomplete on the same page. A bit of context on how the page works: Users can basically add how many steps they want (to add a step, the form uses the Google Autocomplete), and inside each step they can add activities (to add an activity, the form uses also the Google Autocomplete).
I know that by assigning different ids to each form, then getting the element by Id to apply the autocomplete and get the data, would work, but the problem is that each time a user creates a step, it creates a step id, and then an activity form will be assigned to a specific step id, which makes it challenging as in the end I can end up having a lot of different ids.
That's why I was trying a different approach through class instead of id. So let's say I have those 2 forms. They have both the "search_term" class:
<input type="text" class="form-control search_term" placeholder="Search...">
<input type="text" class="form-control search_term" placeholder="Search...">
Then I have basically implemented a for loop so that the program can read all the items that have this class, and then for each item implement the autocomplete + get data about a specific place. The autocomplete works. But then I get "undefined" for the first item when trying to get the data.
<script>
function activatePlacesSearch(){
var input = document.getElementsByClassName('search_term');
var i;
for (i = 0; i < input.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(input[i])
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var result = autocomplete.getPlace();
console.log(result)
if (result != null) {
const location = result['name']
const name = result['name']
const address = result['formatted_address']
const phone_number = result['international_phone_number']
const icon = result['icon']
const types = result['types']
const user_ratings_total = result['user_ratings_total']
const rating = result['rating']
const url = result['website']
const latitude = autocomplete.getPlace().geometry.location.lat();
const longitude = autocomplete.getPlace().geometry.location.lng();
const photos = result['photos'][0].getUrl();
};
});
};
};
</script>
I am a bit stuck on how to solve that. Thanks a lot for your help.

This is just a wild guess, but i´m pretty sure by overwriting variable autocomplete you destroy functionality, maybe try to use dynamic variable-names for each autocomplete:
window['autocomplete_'+i] = new google.maps.places.Autocomplete(input[i])
...
var result = window['autocomplete_'+i].getPlace();
...

Related

Adding text into a text input onKeyPress react.js

I want the string 'Surveillance Capitalism' to be inputted letter by letter into a text input (or something that looks like one) as a user types.
The code works up to the point I try to add the letter into the input, at which point I am told 'Failed prop type: You provided a value prop to a form field without an onChange handler'. Is this method possible? If not what is a good alternative?
Html:
<input
id="search-bar"
type="text"
onKeyPress={this.handleKeyPress}
/>
JS:
//Dictates what is typed in the search bar
(https://stackoverflow.com/questions/27827234/how-to-handle-the-onkeypress-event-in-reactjs)
handleKeyPress = event => {
var firstSearchString = "Surveillance Capitalism";
//Converts firstSearchString into an array of its members (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
var searchStringArray = Array.from(firstSearchString);
//Gets contents of search bar
var searchBar = document.getElementById("search-bar").value;
//Length of that content
var i = searchBar.length;
searchBar.value += searchStringArray[i];
};
Essentially I want to trick the user into thinking they can search whatever they want but when they go to type, my preset query will be entered letter by letter.
The problem is that you are assigning a variable to the search bar:
var searchBar = document.getElementById("search-bar").value;
then altering the variable, to fix your problem i just did this:
handleKeyPress = event => {
var firstSearchString = "Surveillance Capitalism";
var searchStringArray = Array.from(firstSearchString);
for(let i = 0; i < searchStringArray.length; i++) {
document.getElementById("search-bar").value += searchStringArray[i];
}
};
I think that's what you were having trouble with but i'm not sure if i understood the question. I hope this helped
Try the onChange event handler, rather than the onKeyPress handler. That should remove the error you have. They are functionally slightly different, but should accomplish the same thing.

Parsing out muiltipicker in javascript

I have created a form that pulls a person's (peoplepicker) office location automatically from AD via SharePoint's UPS and populates it in the entry field. What I'm having trouble with is pulling multiple individual's office locations and having that parse each individual's respective office location to place that in the field as well. Any ideas or help would be greatly appreciated.
Here is the form, and as you can see it can populate one person's office, but not the other individuals:
After further research, I want to give a thanks to the author of this useful JavaScript SharePoint library: http://spjsfiles.com/index.php?dir=SharePoint%20JavaScripts/spjs-utility/
This library gets a user's information from a SharePoint Master list. You get this with the following function: function fillFieldDemo(){
setFieldValue('Date', '1/1/2017');
setFieldValue('MM','Boston;London');
var userInfo = getUserInfo_v2(_spPageContextInfo.userId);
setFieldValue('Person', userInfo.Name);
setTimeout(function(){
var title = getFieldValue('Person');
setFieldValue('Title', title);
}, 2000);
}
_spBodyOnLoadFunctionNames.push("fillFieldDemo");
Now you can find the users' name, office, etc.
In order to parse through multiple names in an input text box and pull their offices respectively, you can alter this function, like so:
function fillFieldDemo() {
$('.button').on('click', function() {
var subjects = $('.ms-entity-resolved');
var offices = [];
for (var i = 0; i < subjects.length; i++) {
var s = $(subjects[i]).prop("title");
var print = $('.name').val(s);
var userInfo = **getUserInfo_v2**(s);
for (var key in userInfo) {
var value = userInfo.**Office**;
}
offices.push(value);
}
var input = $('.parse').val(offices);
});
}
_spBodyOnLoadFunctionNames.push("fillFieldDemo");
This will allow a user to input multiple names in an input text box and it will parse the names and grab the offices of each of those individuals.

Mozilla Add-on development: Accessing LAST USED or LAST CHANGED fields in password manger

My add-on needs to access stored credentials. In this I want to get the credentials that was changed or used recently. I see that I have LAST USED and LAST CHANGED fields but how do I access those fields in my javascript?
I searched and also tried ( https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/passwords ) but I couldn't get anything.
This is how to get a list of all the currently stored login informations:
var lm = Cc["#mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
var arrOfLogins = lm.getAllLogins();
var numberOfLogins = arrOfLogins.length;
console.info('arrOfLogins:', arrOfLogins);
var myObjs = [];
for (var i=0; i<numberOfLogins; i++) {
var pushObj = {};
pushObj.username = arrOfLogins[i].username;
pushObj.password = arrOfLogins[i].password;
pushObj.hostname = arrOfLogins[i].hostname;
arrOfLogins[i].QueryInterface(Ci.nsILoginMetaInfo);
pushObj.lastUsed = new Date(arrOfLogins[i].timeLastUsed);
pushObj.lastChanged = new Date(arrOfLogins[i].timePasswordChanged);
myObjs.push(pushObj);
}
console.info('myObjs:', myObjs);
If the user has a master password, you have to prompt them to fill it out, otherwise the above iwll fail im pretty sure.

Putting text into textbox in JavaScript from an array

I'm new to JavaScript and I am having problems putting information read from a created array into a text box.I am using Dashcode, but modifying elements in the main.js file as I go along. I have created an array, can get the value from the array, I just can't manage to get the information into the text box.
The line which doesn't work is:
document.getElementById("text").setAttribute("text",textLocation);
where text is the ID of the box, and textLocation is the information I am trying to pass into the text box.
If anyone could help it would be much appreciated.
The rest of the code is below.
var n = null;
var textLocation;
var myArray = new Array("info one","info 2","info 3","info 4","info 5","info 6","info 7","info 8","info 9");
function toPreviousImage(event)
{
var list = document.getElementById("grid").object;
var selectedObjects = list.selectedObjects();
var name = selectedObjects[0].valueForKey("name");
var textinfo = selectedObjects[0].valueForKey("info");
name= name - 1;
if(!n || n == undefined){n=name} else {n--}
textLocation = myArray[n];
document.getElementById("text").setAttribute("text",textLocation);
I believe attribute you want to set is 'value', not 'text'.
document.getElementById("text").setAttribute("value",textLocation);

javascript update controls onload

iv'e got 2 html pages
one performs a "get" method on the other
these pages are duplicates in that they own they both poses a form with the same control types
and control names
when i submit my form from the source page my url string consist of the values appended together after a '?' char
....?txtName=era&txtAge=28&gender=male&langHe=on&langEn=on&select=1
in the detestation page onload i call a function which splits the control names and their values and sets them
// this is called from <body onload="f();">
function f() {
var st = new String(location.search);
st = st.substring(1, st.length);
var input = st.split('&');
var value;
var ctrl;
var val;
var _control;
for (var i = 0; i < input.length; i++)
{
value = input[i].substring(0, input[i].length);
ctrl = value.substring(0, value.indexOf('='));
val = value.substring(value.indexOf('=') + 1, value.length);
_control = document.getElementsByName(ctrl);
_control.value = val;
}
}
i debugged this function and checked that every thing is put in to place as it should
the problem is that after the value are set to the controls
they do not appear on the page , as if they didn't get set at all
additionally in Google chrome i get a "Aw,Snap!" Error after these actions (Aw Snap happens only when i debug )
i'm new to java-script and i'm guessing there's a problem with the way i'm assigning these values , i tried also just the first control which is a text type input and it also does not get updated .
any idea's on why this doesn't work ?
thanks in advance
eran.
Try changing the last line to:
_control[0].value = val;
UPDATE:
It would be a lot easier if you used jQuery:
$('[name='+ctrl+']').val(val);

Categories