This code is trying to insert the data from input elements on the page into a Meteor Collection Task1
I am getting "App is crashing error" because of the Tasks1.insert line. Why and how can I fix it?
I need to get the element name and value as the key:value pair for the Document being inserted. Thanks
Template.footer.events({
'click button': function () {
if ( this.text === "SUBMIT" ) {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
Tasks1.insert({inputs[i].name: inputs[i].value});
}
}
}
});
inputs[i].name cannot be used as a key of an object literal, because it's a variable and we can only use strings for defining properties in an object literal.
Like this it should work (it's the most common workaround):
for (var i = 0; i < inputs.length; i++) {
// First define a variable
var params = {};
// Then you can use a variable (or a function) to set the key
params[inputs[i].name] = inputs[i].value;
Tasks1.insert(params);
}
Related
working with the google places api and cannot figure why autocomplete is returning undefined here on call to get places.
what developer tools shows is.
address_components is what should be returned on a call to autocomplete.getPlace
Unable to get property 'address_components' of undefined or null reference
function initAutoCompleteDynamic() {
var slideID = 99;
var idx = 99 - slideID;
var propcount = 5;
for (var i = 0; i < propcount; i++) {
var propaddress = "prop1address" + i;
var autocomplete = autocomplete + i;
autocomplete = new google.maps.places.Autocomplete(
document.getElementById(propaddress)),
{ types: ['geocode'] };
autocomplete.addListener('place_changed', fillinAddressDynamic);
}
}
and in fillinAddressDynamic
var place=autocomplete.getPlace():
for (var i = 0; i < place.address_components.length; i++) {
alert("i am in the loop");
var addressType = place.address_components[i].types[0];
var field = addressType;
var completeaddress1 = '';
var propaddress = 'prop1address' + i;
var strnum = 'streetnumber' + i;
CR(i);//calling component resolver.
if (componentFormProduction[addressType]) {
var val = place.address_components[i][componentFormProduction[addressType]];
document.getElementById(CR[addressType]).value = val;
if (field == "street_number") {
var streetnum = document.getElementById(strnum).value = val;
}
if (field == "route") {
if (streetnum) {
completeaddress1 = streetnum + ' ' + val;
}
else {
completeaddress1 = val;
}
document.getElementById('prop1address0').value = completeaddress1;
}
}
}
This would happen if the user (or you) hits Enter without clicking on a suggestion.
Typically the sequence of event is like this:
user enters input
JavaScript queries Autocomplete for suggestions
user clicks on a suggestion
JavaScript queries Details, replaces user input with Details responses' fields (incl. address_components) and fires the places_changed event
handler for places_changed will obtain the Place object from Details response by calling getPlace()
However, it may also be like this:
user enters input
JavaScript queries Autocomplete for suggestions
user disregards suggestions and hits Enter without clicking on one
JavaScript fires the places_changed event without querying Details or modifying user input
handler for places_changed calls getPlace() and gets a nearly empty Place object, with only the name field containing the raw user input.
It is for you to decide what to do with raw user input, here are some examples:
This tool uses the JavaScript Geocoding service to search for that input:
https://google-developers.appspot.com/maps/documentation/utils/geocoder/
This example (address form) does nothing with it:
https://google-developers.appspot.com/maps/documentation/javascript/examples/places-autocomplete-addressform
This (very basic) example will show an error message reporting no details:
https://google-developers.appspot.com/maps/documentation/javascript/examples/full/places-autocomplete
I have a function that creates a dictionary based on a series of values from a sheet. I then try to pull one of the values from that sheet using a key. It works fine to log to the console. However, in an if statement, it says syntax error and nothing else. I cannot figure it out. Here is the function and the code that crashes. This problem only occurs in the for loop, and does not occur outside of it.
//creates dictionary
function columnLocationWithNotation(notation) {
var spreadsheet = SpreadsheetApp.openByUrl();
var sheet = spreadsheet.getActiveSheet();
var data = sheet.getDataRange();
var cells = data.getValues();
var dictionary = {};
switch (notation) {
case "zeroIndex":
for (var i = 0; i < sheet.getLastRow(); i++) {
dictionary[cells[i][0]] = cells[i][1]
}
return dictionary
break;
case "regularIndex":
for (var i = 0; i < sheet.getLastRow(); i++) {
dictionary[cells[i][0]] = cells[i][2]
}
return dictionary
break;
case "string":
for (var i = 0; i < sheet.getLastRow(); i++) {
dictionary[cells[i][0]] = cells[i][3]
}
return dictionary
break;
}
}
var master0indexDictionary = columnLocationWithNotation("zeroIndex")
for (var i = 1; i =< (sheet.getLastRow() - 1); i++) {
var phone = master0indexDictionary["Tutor Name"]
if (cells[i][phone] === phoneNumber) { //LINE WITH SYNTAX ERROR
//do something
}
It's not the highlighted line that is causing the problem, even though there are many other issues with your script. There's no '=<' operator in JavaScript. Use '<=' instead:
for (var i = 1; i <= (sheet.getLastRow() - 1); i++) {
Also, as Tanaike pointed out, your 'cells' variable is only defined in the context of your 'columnLocationWithNotation(notation)' function and will not be accessible from the global context. Globally-defined variables are visible from the functions you declare inside the global object, but not vice versa. Same applies to the 'sheet' variable. The 'phoneNumber' variable doesn't seem to be defined, at least not in the snippet of code you provided.
Note that putting 'break' after 'return' statements is redundant.
return dictionary;
break;
You can just return out of 'switch' statement without using breaks, or leave the breaks and put a single 'return' statement after 'switch'.
Finally, always put a semicolon at the end of the line. Doing so will help you avoid many potential pitfalls and issues with JS parser. I noticed several instances where you omitted the semicolon:
return dictionary
break;
var phone = master0indexDictionary["Tutor Name"]
For example, the following code will break if you don't have a habit of putting the semicolon in its rightful place
var a = {name: 'John'} //no semicolon
[a].forEach(function(element) {
Logger.log(element); //logs undefined
})
The JS parser treats this code as one line, so 'a' will still be 'undefined' by the time you call the 'forEach()' loop on the array.
I'm trying to change the radius category/type filter for a checkbox, so I changed the var type to an array.
ORIGINAL WORKING:
var type;
for (var i = 0; i < document.controls.type.length; i++){
if (document.controls.type[i].checked){
type = document.controls.type[i].value;
}
}
startBox.setBounds(map.getBounds());
var search = {
// keyword: 'comocomo', // not needed with the autocomplete / startBox
bounds: map.getBounds()
};
if (type != 'establishment'){
search.types = [ type ];
}
places.search(search, function(placesArr, status){
THE ONE WITH THE ARRAY NOT WORKING: edited:
var type=[];
for (var i = 0; i < document.controls.type.length; i++){
if (document.controls.type[i].checked){
type.push(document.controls.type[i].value)
}
}
startBox.setBounds(map.getBounds());
var search = {
bounds: map.getBounds()
};
var quotedAndCommaSeparated = "'" + type.join("','") + "'";
alert(quotedAndCommaSeparated); // 'establishment','restaurant','lodging'
search.types = [ quotedAndCommaSeparated ];
I made many tests, and I don't see what I'm doing wrong. the map doesn't even show.
What's this meant to be, doesn't look like valid Javascript to me:
var type[];
Should be
var type = [];
Fix the javascript errors in your code otherwise the map won't show up.
Update:
What you have in quotedAndCommaSeparated is a string like "'a','b','c'" that looks a bit like the contents of an array: ['a','b','c']. But it's not an array, it's just a single string. If you check the length of your search.type array, I'm guessing it equals 1.
What you can do is split your string on the comma to turn it into an array:
search.types = quotedAndCommaSeparated.split(",");
I am calling a web Method from javascript. The web method returns an array of customers from the northwind database. The example I am working from is here: Calling Web Services with ASP.NET AJAX
I dont know how to write this javascript method: CreateCustomersTable
This would create the html table to display the data being returned. Any help would be appreciated.
My javascript
function GetCustomerByCountry() {
var country = $get("txtCountry").value;
AjaxWebService.GetCustomersByCountry(country, OnWSRequestComplete, OnWSRequestFailed);
}
function OnWSRequestComplete(results) {
if (results != null) {
CreateCustomersTable(results);
//GetMap(results);
}
}
function CreateCustomersTable(result) {
alert(result);
if (document.all) //Filter for IE DOM since other browsers are limited
{
// How do I do this?
}
}
else {
$get("divOutput").innerHTML = "RSS only available in IE5+"; }
}
My web Method
[WebMethod]
public Customer[] GetCustomersByCountry(string country)
{
NorthwindDALTableAdapters.CustomersTableAdapter adap =
new NorthwindDALTableAdapters.CustomersTableAdapter();
NorthwindDAL.CustomersDataTable dt = adap.GetCustomersByCountry(country);
if (dt.Rows.Count <= 0)
{
return null;
}
Customer[] customers = new Customer[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
NorthwindDAL.CustomersRow row = (NorthwindDAL.CustomersRow)dt.Rows[i];
customers[i] = new Customer();
customers[i].CustomerId = row.CustomerID;
customers[i].Name = row.ContactName;
}
return customers;
}
Try to look what is the result variable value in debug mode. If the structure seems the structure that i'm imagining, something like this could work:
function CreateCustomersTable(result) {
var str = '<table>';
str += '<tr><th>Id</th><th>Name</th></tr>';
for ( var i=0; i< result.length; i++){
str += '<tr><td>' + result[i].CustomerId + '</td><td>' + result[i].Name + '</td></tr>';
}
str += '</table>';
return str;
}
And then You can do somethig like this:
var existingDiv = document.getElementById('Id of an existing Div');
existingDiv.innerHTML = CreateCustomersTable(result);
I wish this help you.
Something like this, assuming you have JSON returned in the "result" value. The "container" is a div with id of "container". I'm cloning nodes to save memory, but also if you wanted to assign some base classes to the "base" elements.
var table = document.createElement('table');
var baseRow = document.createElement('tr');
var baseCell = document.createElement('td');
var container = document.getElementById('container');
for(var i = 0; i < results.length; i++){
//Create a new row
var myRow = baseRow.cloneNode(false);
//Create a new cell, you could loop this for multiple cells
var myCell = baseCell.cloneNode(false);
myCell.innerHTML = result.value;
//Append new cell
myRow.appendChild(myCell);
//Append new row
table.appendChild(myRow);
}
container.appendChild(table);
You should pass the array as JSON or XML instead of just the toString() value of it (unless that offcourse is returns either JSON oR XML). Note that JSOn is better for javascript since it is a javascript native format.
Also the person who told you that browser other then IE can not do DOM manipulation should propably have done horrible things to him/her.
If your format is JSON you can just for-loop them and create the elements and print them. (once you figured out what format your service returns we can help you better.)
I'm creating a JsonArray such as:
JsonArray jsonValues = new JsonArray();
for( int i = 0; i < values.Count; i++ )
{
var someSingleValue = values[i];
jsonValues.Add( string.Format( "Name: {0}", someSingleValue ) );
}
After that I'm shipping json values to my javascript in .aspx page via call:
HtmlPage.Window.Invoke("call", jsonValues);
The call works and it gets there, however I have no idea how to iterate over those values, i.e extract them.
I've tried: (in javascript)
for (var x in somevalues){ alert(somevalues); }
I also tried:
for(var i = 0; i < somevalues.length; i++) {
alert(somevalues[i]);
}
but it crashes.(in both cases)
any ideas?
Are you using the eval method to serialize the string to a JSON object?
function call(somevalues){
//somevalues is currently just a string.
var results = eval("(" + somevalues +")");
//results now should contain your array as a JSON object.
//and you should be able to iterate over it at this point.
for(var i = 0; i < results.length; i++){
alert(results[i]);
}
}
Assuming somevalues is truly an array, you do it like this:
for(var i = 0; i < somevalues.length; i++) {
// do something with somevalues[i]
}
What you did was tell JavaScript to iterate over the properties of the somevalues object, which is similar, but not the same, as the iteration using a regular for loop.
EDIT: I am willing to bet your variable, somevalues is a string. Just do alert(somevalues) and see what happens.