Access class properties in javascript from class method - javascript

this my first try doing the mvc model with classes in javascript.
With the method getFormValues() of the model object of my controller object app I want to read the values of all the input files . Then I want to save them to the form values property of the model object of my controller object. This doesn`t work!
The line console.log(app.model.getFormValues()); shows me the Array with the form values.
The line console.log(app.model.formValues); shows me an empty Array.
How can I store the array from the method getFormValues in the property formValues of the model object?
My HTML:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<form>
<div class="row">
<div class="col">
<input type="text" class="form-control" placeholder="First name">
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Last name">
</div>
</div>
</form>
<button id="verification"> Verify</button>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="js.js"></script>
</body>
</html>
My JS/Jquery:
class Model {
constructor() {
this.formValues = this.getFormValues();
}
getFormValues() {
let $inputs = $("input");
var formValues = [];
$inputs.each(function(index) {
let value1 = $(this).val();
formValues.push(value1);
});
return formValues;
}
}
class View {
constructor() {}
}
class Controller {
constructor(model, view) {
this.model = model
this.view = view
}
}
const app = new Controller(new Model(), new View());
check = function () {
console.log(app.model.getFormValues());
console.log(app.model.formValues);
}
$("#verification").on("click", check);
Greetings and thanks in advance
Fabian

Your problem is based on the creation of the app constant.
You create the app constant when you first load the page.
At this point the inputs are empty so are they for the app constant.
Edit: update your variable when you click your button like in my snippet.
class Model {
constructor() {
this.formValues = this.getFormValues();
}
getFormValues() {
let $inputs = $("input");
var formValues = [];
$inputs.each(function(index) {
let value1 = $(this).val();
formValues.push(value1);
});
return formValues;
}
}
class View {
constructor() {}
}
class Controller {
constructor(model, view) {
this.model = model
this.view = view
}
}
const app = new Controller(new Model(), new View());
check = function () {
app.model.formValues = app.model.getFormValues();
console.log(app.model.getFormValues());
console.log(app.model.formValues);
}
$("#verification").on("click", check);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="row">
<div class="col">
<input type="text" class="form-control" placeholder="First name">
</div>
<div class="col">
<input type="text" class="form-control" placeholder="Last name">
</div>
</div>
</form>
<button id="verification"> Verify</button>

Related

My UserForm doesnt give an Output (GoogleSheets)

i am very new to google sheets and tryed to use an Userform to fill in my Sheets. But every time, i click submit it just freezes and nothing more happends...
https://docs.google.com/spreadsheets/d/13LdDIMvWpVkj5rom2fHV25FtYvbOcnKr4cZF84nITYQ/edit?usp=sharing
And the code:
HTML:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<form>
<div class="form-group">
<label for="name" class="form-label">name</label>
<input type="text" class="form-control" id="name">
</div>
<div class="form-group">
<label for="price" class="form-label">price</label>
<input type="text" class="form-control" id="price">
</div>
<button type="submit" class="btn btn-primary" id="add" >Submit</button>
</form>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
-->
<script>
function afterButtonClicked(){
var item = document.getElementById("name");
var price = document.getElementById("price");
google.script.run.addnewrow(name,price);
}
document.getElementById("add").addEventListener("click",afterButtonClicked);
<script>
</body>
</html>
Here are my functions:
function addnewRow(nameprice) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Results");
ws.appendRow([name,price]);
}
I dont know if its important, but here is the cutom menu:
function loadForm() {
const htmlForSidebar = HtmlService.createTemplateFromFile("uform");
const htmlOutput = htmlForSidebar.evaluate();
const ui = SpreadsheetApp.getUi();
ui.showSidebar(htmlOutput);
}
function createMenu(){
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu("Meine Forms");
menu.addItem("Show UserForm","loadForm");
menu.addToUi();
}
function onOpen(){
createMenu();
}
Thank you!
There are few modification in your code:-
In HTML file you've syntax error, you didn't used </script>.
You're passing wrong variable as a argument in addnewRow while running it through google.script.run.
You're trying to run function which actually doesn't exist in server-side.
Parameter in addnewRow function is missing comma , in server-side.
Sheet you're trying to access in ss.getSheetByName("Results") doesn't exist.
Do following modifications in <script> tag of client side code(HTML File):-
<script>
function afterButtonClicked(){
var item = document.getElementById("name").value;
var price = document.getElementById("price").value;
google.script.run.addnewRow(item,price);
}
document.getElementById("add").addEventListener("click",afterButtonClicked);
</script>
And replace this :-
function addnewRow(nameprice) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Results");
ws.appendRow([name,price]);
}
with this :-
function addnewRow(name,price) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Results");
ws.appendRow([name,price]);
}
and change/add the sheet name as Result in Spreadsheet.

MDC - Text Input can't be initialized

I'm setting up a text input with MDC but when I'm initializing with JS it comes out this error:
This is my code:
// MDC
const mdc = window.mdc;
// Auto init
mdc.autoInit();
$('.mdc-text-fields').each((index, element) => {
const textField = mdc.textField.MDCTextField.attachTo($(element)[0]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/material-components-web#4.0.0/dist/material-components-web.min.css">
<script src="https://unpkg.com/material-components-web#latest/dist/material-components-web.min.js">
<div class="mdc-text-field">
<input class="mdc-text-field__input" type="text">
<label class="mdc-floating-label" for="class_name">Nome classe</label>
<div class="mdc-line-ripple"></div>
</div>
Can you help me?
Thanks
Strangely, it worked now removing const textField =...
This is the new JS code:
// MDC
const mdc = window.mdc;
// Auto init
mdc.autoInit();
$('.mdc-text-fields').each((index, element) => {
mdc.textField.MDCTextField.attachTo(element);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/material-components-web#4.0.0/dist/material-components-web.min.css">
<script src="https://unpkg.com/material-components-web#latest/dist/material-components-web.min.js">
<div class="mdc-text-field">
<input class="mdc-text-field__input" type="text">
<label class="mdc-floating-label" for="class_name">Nome classe</label>
<div class="mdc-line-ripple"></div>
</div>
Reference for this solution: https://stackoverflow.com/a/52021265/7520280

update the boolean value in md-select using angular material

am struggled in md-select model update when user changes the value need to update the flag as true.Actually i have to iterate the length of the model in md-select and in md-options i show like 1,2...5. if user changes the value in drop down means respective flag set to true other should be in false.kindly help me out this problem. following is my code and kindly tell me where i did the logical mistake:
<html lang = "en">
<head>
<link rel = "stylesheet"
href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
</style>
<script language = "javascript">
angular
.module('testApp', ['ngMaterial'])
.controller('myCTRL', myCTRL);
function myCTRL ($scope) {
$scope.chooseValue =false;
$scope.selectedValue = 1;
$scope.testValue = [
{ isEnabled: false},
{ isEnabled: false },
{ isEnabled: false }
];
$scope.submitvalue = function(){
console.info($scope.testValue)
$scope.testValue[$scope.selectedValue].isEnabled = true;
console.info($scope.finalvalue)
}
}
</script>
</head>
<body ng-app = "testApp">
<div id = "inputContainer" class = "inputDemo"
ng-controller = "myCTRL as ctrl" ng-cloak>
<form role="form" name="deviceForm">
<div>
<md-input-container >
<label>select flags want to enable</label>
<md-select ng-model="selectedValue" >
<md-option ng-repeat="(key,value) in testValue">{{key}}</md-option>
</md-select>
</md-input-container>
</div>
</form>
<input type="submit" ng-click="submitvalue()">
</div>
</body>
</html>
Thanks in advance.
You can simply create a new copy of testValue object into finalValue variable, then do the boolean assignments in that and use. Please refer the below code.
console.info($scope.testValue)
$scope.finalValue = angular.copy($scope.testValue);
$scope.finalValue[$scope.selectedValue].isEnabled = true;
console.info($scope.finalValue)
We create a new copy of testValue using method angular.copy() and assign it to final value. Then we use your logic to assign the respective indexed boolean to true.
The problem with your original code, is that you are showing finalValue, without it being even defined as a variable and also no data manipulations were done to it!
Please refer the below working snippet, and let me know if you face any issues implementing the below code!
angular
.module('testApp', ['ngMaterial'])
.controller('myCTRL', myCTRL);
function myCTRL($scope) {
$scope.chooseValue = false;
$scope.finalValue = {};
$scope.selectedValue = 1;
$scope.testValue = [{
isEnabled: false
},
{
isEnabled: false
},
{
isEnabled: false
}
];
$scope.submitvalue = function() {
console.info($scope.testValue)
$scope.finalValue = angular.copy($scope.testValue);
$scope.finalValue[$scope.selectedValue].isEnabled = true;
console.info($scope.finalValue)
}
}
<html lang="en">
<head>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<style>
</style>
</head>
<body ng-app="testApp">
<div id="inputContainer" class="inputDemo" ng-controller="myCTRL as ctrl" ng-cloak>
<form role="form" name="deviceForm">
<div>
<md-input-container>
<label>select flags want to enable</label>
<md-select ng-model="selectedValue">
<md-option ng-repeat="(key,value) in testValue">{{key}}</md-option>
</md-select>
</md-input-container>
</div>
</form>
<input type="submit" ng-click="submitvalue()">
</div>
</body>
</html>

AngularJS 2 OnSelect Returns Error

I'm trying to follow the Angular 2 tutorial, which is in TypeScript, but in JavaScript. Unfortunately I've hit a snag and I can't find a solution searching online. Right now I'm on the Master/Detail step. I'm defining an onSelect element but when I define my onSelect function I get back the following error:
Uncaught TypeError: Cannot read property 'annotations' of undefined
Here is my code:
app.component.js:
(function(app) {
app.AppComponent =
ng.core.Component({
selector: 'my-app',
template:`
<h2>My Heros</h2>
<ul class="heroes">
<li *ngFor="let hero of Heroes" [class.selected]="hero === selectedHero" (click)="onSelect(hero)">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
<div *ngIf="selectedHero">
<h2>{{selectedHero.name}} details!</h2>
<div><label>id: </label>{{selectedHero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="selectedHero.name" placeholder="name"/>
</div>
</div>
`
})
.Class({
constructor: function() {
this.title = 'Tour of Heros';
this.Heroes = Heroes;
this.onSelect(hero) {
this.selectedHero = hero;
};
}
});
})(window.app || (window.app = {}));
function Hero (id, name) {
this.id = id;
this.name = name;
};
var Heroes = [
new Hero(11, 'Mr. Nice'),
new Hero(12, 'Narco'),
new Hero(13, 'Bombasto'),
new Hero(14, 'Celeritas'),
new Hero(15, 'Magneta'),
new Hero(16, 'RubberMan'),
new Hero(17, 'Dynama'),
new Hero(18, 'Dr. IQ'),
new Hero(19, 'Magma'),
new Hero(20, 'Tornado')
];
index.html:
<html>
<head>
<title>Angular 2 QuickStart JS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- 1. Load libraries -->
<!-- IE required polyfill -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/rxjs/bundles/Rx.umd.js"></script>
<script src="node_modules/#angular/core/bundles/core.umd.js"></script>
<script src="node_modules/#angular/common/bundles/common.umd.js"></script>
<script src="node_modules/#angular/compiler/bundles/compiler.umd.js"></script>
<script src="node_modules/#angular/platform-browser/bundles/platform-browser.umd.js"></script>
<script src="node_modules/#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js"></script>
<!-- 2. Load our 'modules' -->
<script src='app/app.component.js'></script>
<script src='app/main.js'></script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
main.js:
(function(app) {
document.addEventListener('DOMContentLoaded', function() {
ng.platformBrowserDynamic.bootstrap(app.AppComponent);
});
})(window.app || (window.app = {}));
If I remove the this.onSelect(hero) {this.selectedHero = hero;}; it works fine, minus the ability to select an element. I've tried defining selectedHero with a default value and still the same error occurs. How do I define the onSelect function?
I guess
this.onSelect(hero) {
should be
this.onSelect = function (hero) {

Updating a variable inside Service

Right I've got a really dumb one for you, and I've been looking at this code all day with no result.
I have a simple textbox which goes through a controller and updates a variable inside a service (The service will eventually fetch/update data from somewhere else).
At the moment, I am able to retrieve the variable value all the way to the view and it works, but the textbox is unable to update the variable inside the service in order to then display the new variable value in the view again....
I really appreciate any help and hope I have made sense!!!
// APP/APP.JS
(function(){
var app = angular.module('appMod', ['ngRoute', 'ngAnimate']);
app.config(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'introController',
templateUrl: 'app/partials/intro.html'
})
.otherwise({ redirectTo: '/' });
});
app.controller('nameController', function($scope, dataService) {
var nameValue;
this.name = dataService.getName();
this.submitName = function(nameVal) {
nameValue = this.nameCtrl.nameVal;
dataService.setName(nameValue);
};
});
app.controller('introController', function($scope, dataService) {
this.name = dataService.getName();
});
app.service('dataService', function () {
var name = "f";
this.getName = function() {
return name;
};
this.setName = function(nameVal) {
name = nameVal;
};
});
})();
<!-- INDEX.HTML -->
<!DOCTYPE html>
<html ng-app="appMod">
<head>
<link rel="stylesheet" type="text/css" href="content/css/normalize.css">
<link rel="stylesheet" type="text/css" href="content/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="content/css/style.css">
<link rel="stylesheet" type="text/css" href="content/css/animation.css">
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="scripts/angular.min.js"></script>
<script type="text/javascript" src="scripts/angular-route.min.js"></script>
<script type="text/javascript" src="scripts/angular-timer.min.js"></script>
<script type="text/javascript" src="scripts/angular-animate.min.js"></script>
<script type="text/javascript" src="app/app.js"></script>
</head>
<body>
<div class="container">
<div class="row" ng-controller="nameController as nameCtrl">
<img src="content/images/sitelogo.png" class="logo">
<h2 class="welcomeMessage fade">Welcome <span class="fade" ng-show="!nameCtrl.name == ''">{{nameCtrl.name}}</span><span class="inline fade" ng-hide="nameCtrl.name !== ''">Friend</span> <small>(We like to get personal!)</small></h2>
<div class="namebox fade">
<h2>Welcome <small class="fade">Please type your name</small></h2>
<form class="fade">
<div class="form-group">
<input type="text" class="form-control" ng-model="nameCtrl.nameVal" autofocus>
</div>
<button type="submit" style="width:100%;" class="btn btn-default fade" ng-click="nameCtrl.submitName()" >Submit</button>
</form>
</div>
</div>
</div>
<div ng-view></div>
</body>
</html>
You need to be binding to name and not nameVal on your input
Then just pass that in your setName call, i don't think the rest of the code is needed in there, you can get rid of the nameValue var too.
this.submitName = function() {
dataService.setName(this.name);
};
The nameValue var is local to the controller and not available on the $scope to bind to your view, so even though you were changing it, the view didn't know about it as it couldn't see that var.

Categories

Resources