Knockoutjs program is not working - mvvm

I am new to Knockoutjs, starting with http://learn.knockoutjs.com/ tutorial but the same when i am trying in local it is not working.
Do i need to write model and view in separate file or same, My question is how to run first knockout program.
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js'></script>
<script type="text/javascript">
// Here's my data model
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work​​​​​​​​​​​​​​​​​​
</script>
</head>
<body>
<div class='liveExample'>
<p>First name: <input data-bind='value: firstName' /></p>
<p>Last name: <input data-bind='value: lastName' /></p>
<h2>Hello, <span data-bind='text: fullName'> </span></h2>
</div>​
</body>
</html>

You should put ko.applyBindings to the end of page. Here is a quote from official documentation:
To activate Knockout, add the following line to a block:
ko.applyBindings(myViewModel);
You can either put the script block at the bottom of your HTML
document, or you can put it at the top and wrap the contents in a
DOM-ready handler such as jQuery’s $ function.
So code should look as follow:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js'></script>
</head>
<body>
<div class='liveExample'>
<p>First name: <input data-bind='value: firstName' /></p>
<p>Last name: <input data-bind='value: lastName' /></p>
<h2>Hello, <span data-bind='text: fullName'> </span></h2>
</div>​
<script type="text/javascript">
// Here's my data model
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work​​​​​​​​​​​​​​​​​​
</script>
</body>
</html>
Here is working fiddle: http://jsfiddle.net/vyshniakov/s2LSE/

Related

Show method from resource controller returns null

I'm having trouble with learning laravel and decided to ask my question here since I can't find an answer via Google etc.
I am trying to return a client from the database via Id, maybe later via name.
This is my form:
<<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Klant invoeren</title>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
</head>
<body>
<p><<form action="{{route('client/'.$client->id.'/show/')}}"
method="get">
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="price">Achternaam:</label>
<input type="text" class="form-control" name="id">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
{{csrf_field()}}
<button type="submit" class="btn btn-success" style="margin-
left:38px">Zoek klant</button>
</div>
</div>
</form></p>
</body>
</html>
Which redirects to:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Klant invoeren</title>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
</head>
<body>
<div class="container">
<h2>Voer een klant in</h2><br />
<h1>Showing {{ var_dump($client) }}</h1>
</div>
</body>
</html>`
And this is the show method from the Clientcontroller:
public function show($id)
{
$client = Client::find($id);
return view('clients.show', compact('client'));
}
This is the route I'm using:
Route::get('client/{id}/show','ClientController#show');
Can someone spot my mistake, because I can't after messing with this the last few hours.
EDIT: updated code and added the route, now getting the error that the client variable isn't defined in the
You must echo the client id in the form action. So, remove the inverted comma from $client->id. Use the following code :
<form action="{{action('ClientController#show', $client->id)}}"
method="get">
Additionally, remove backtick from the code. Use the following code :
public function show($id)
{
$client = Client::find($id);
return view('clients.show', compact('client'));
}
In your routes/web.php
Route::get('client/{id}/show','ClientController#show');
In your form:
<form action="{{URL::to('client/'.$client->id.'/show/')}}"
method="get">
In your controller:
public function show($id)
{
$client = Client::find($id);
return view('clients.show', compact('client'));
}
In your Client Controller make sure you use the Model that you are referencing to
Assuming App\Client.php Change it to App\User.php if you are referring to user
ClientController
use App\Client;
public function show($id)
{
$client = Client::find($id);
return view('clients.show', compact('client'));
}
Now you can fetch the client model with $client For example $client->id
Make sure you pass the {id} parameter in the route

Firebase Authorization and Standard Google App Engine - cannot login or signup

I have a google app engine and I recently decided to add app engine to it. I have gone through the steps, have imported my google project into firebase, added all the initialization code, and some temp functions for logging in and signing up. However, the app never goes past the points where I try to log in. I have been searching everywhere and trying everything I can. I'm sure I'm just missing something small, but could use another set of eyes. Thanks.
Here is my html file:
<!DOCTYPE html>
<html>
<head>
<title>Hello Endpoints!</title>
<script type="text/javascript" src="/js/base.js"></script>
<!-- SCRIPT FOR FIREBASE -->
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-database.js"></script>
<script type="text/javascript" src="/js/firebaseApp.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="/bootstrap/css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="/bootstrap/css/bootstrap-responsive.css">
<link type="text/css" rel="stylesheet" href="/css/style.css">
</head>
<body>
<div class="container">
<input id="txtEmail" type="email" placeholder="Email">
<input id="txtPassword" type="password" placeholder="Password">
<button id="btnLogin" class="btn btn-action" onclick="loginEvent()">
Log in
</button>
<button id="btnSignUp" class="btn btn-secondary" onclick="signupEvent()">
Sign Up
</button>
<button id="btnLogout" class="btn btn-action hide">
Log out
</button>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
projectId: "<PROJECT_ID>",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
firebase.initializeApp(config);
</script>
</div>
<div class="container">
<form action="javascript:void(0);">
<h2>Add Asteroid</h2>
<div><span class="label">Name: </span><input id="asteroidName" /></div>
<div><span class="label">Diameter: </span><input id="asteroidDiam" /></div>
<div>Dimensions:</div>
<div><span class="dimlabel">Length: </span><input id="asteroidLength" /></div>
<div><span class="dimlabel">Width: </span><input id="asteroidWidth" /></div>
<div><span class="dimlabel">Height: </span><input id="asteroidHeight" /></div>
<div><span class="label">Mean Distance From Sun: </span><input id="asteroidDist" /></div>
<div><input id="addAsteroid" type="submit" class="btn btn-small" value="Submit"></div>
</form>
<form action="javascript:void(0);">
<h2>Refresh Asteroids</h2>
<div><input id="listAsteroids" type="submit" class="btn btn-small" value="Refresh"></div>
</form>
<table id="AsteroidTable">
<tr>
<th>Asteroid</th>
<th>Diameter</th>
<th>Dimensions</th>
<th>Mean Distance From Sun</th>
</tr>
</table>
<script type="text/javascript">
function init() {
google.devrel.samples.hello.init('//' + window.location.host + '/_ah/api');
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
</div>
</body>
</html>
And here is my FirebaseApp.js:
function loginEvent()
{
const email = document.getElementById('txtEmail');
const pass = document.getElementById('txtPassword');
email.value = "HELLO";
email.value = firebase.app().name;
pass.value = "NO";
firebase.auth().signInWithEmailAndPassword(email, pass)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
});
pass.value = "YES"
}
function signupEvent()
{
const email = document.getElementById('txtEmail');
const pass = document.getElementById('txtPassword');
firebase.auth().createUserWithEmailAndPassword(email, pass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
}
I was changing the values of the email and password just to make sure I was reaching that point. printing out the value of firebase.app().name returns [DEFAULT]. I also made sure email/password option was selected in Firebase. Thank you for any help you can provide.
You only need to include https://www.gstatic.com/firebasejs/4.3.1/firebase.js which contains all the modules needed. No need to include all the others: firebase-app.js, firebase-auth.js, etc.
Also signInWithEmailAndPassword and createUserWithEmailAndPassword accept string arguments. You are passing input elements instead. There should errors thrown in the console because of this. So instead of email, pass email.value.

Google map geocoding with form submit

Problem:
I have a form with some input fields, and i'm trying to convert the adress to geocode before it submits to my controller (using Spring MVC). But somehow my geolocation field is empty after the conversion... And for some reason the same code does work on a form without a submit. Can someone help me please? Thanks a lot!
Code:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="domain.Location"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Leuven Speaks</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
</head>
<body>
<jsp:include page="header.jspf"/>
<script type="text/javascript" src="<c:url value="/js/style.js" />"></script>
<form name="addLocation" method="POST" action="addLocation.htm" commandName="location" onsubmit="changeAdress()">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Adres</td>
<td><input type="text" id="adress" name="adress"/></td>
</tr>
<tr>
<td><input type="text" id="geolocation" name="geolocation"/></td>
</tr>
</table>
<input type="hidden" name="id" value="${location.id}"/>
<input type="submit" name="action" value="Save"/>
<input type="submit" name="action" value="Cancel"/>
</form>
</body>
<script type="text/javascript">
function changeAdress(){
var adres = document.getElementById("adress").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': adres}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
document.addLocation.geolocation.value = latitude + " " + longitude;
}
});
//geolocation is empty...
alert(document.getElementById("geolocation").value);
return true;
}
</script>
</html>
Geocoding is asynchronous, submit the form it the callback routine.
function changeAdress(){
var adres = document.getElementById("adress").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': adres}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
document.addLocation.geolocation.value = latitude + " " + longitude;
alert(document.getElementById("geolocation").value);
document.addLocation.submit();
} else alert("geocode failed:"+status);
});
return false;
}
proof of concept fiddle

Backbone: el: $ is not defined

So i have this code, (i'm learning Backbone, but the console tells me: "Uncaught ReferenceError: $ is not defined", and i don't have any idea why, i have the exact code of the video tutorial, the error is in this line: el : $('#container')
Here is my code:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Backbone Project</title>
<script src="lib/underscore.js" type="text/javascript"></script>
<script src="lib/backbone.js" type="text/javascript"></script>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<script type="text/template" id="task_template">
<label>Task: </label>
<input type="text" id="task_desc"/>
<input type="button" value="Add Task" id="btn"/>
</script>
<div id="container"></div>
<script type="text/javascript">
Task = Backbone.View.extend({
el : $('#container'),
initialize: function(){
this.render();
},
render: function(){
var template = _.template($('#task_template').html(), {});
this.$el.html(template);
}
});
var task = new Task();
</script>
</body>
</html>
The example is using jQuery to select DOM elements, add the library to your head...
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
<!-- load other libraries that depend on jquery *after* jquery -->
<script src="lib/underscore.js" type="text/javascript"></script>
<script src="lib/backbone.js" type="text/javascript"></script>
<!-- ... time passes ... -->
<script type="text/javascript">
// use jQuery onReady wrapper to ensure DOM has loaded before
// executing JS that might depend on DOM elements, and scripts to exist
$(function(){
Task = Backbone.View.extend({
el : $('#container'),
initialize: function(){
this.render();
},
render: function(){
var template = _.template($('#task_template').html(), {});
this.$el.html(template);
}
});
var task = new Task();
});
</script>

How do I get the values from dynamically created form fields and reference them for other form functions?

Here is what I have so far...
<html>
<head>
<title>addForm</title>
<link href="css/addForm.css" rel="stylesheet" type="text/css">
<link href="favicon.ico" rel="icon" type="image/x-icon" />
<script type="text/javascript" src="../lib/jquery/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../lib/jquery/jquery.autocomplete.min.js"></script>
</head>
<body>
<div>
<form id="addForm" name="addForm" method="post" action="">
...
<div id="container">
<p id="add_field">
<label>Add A Class Code</label>It may take a moment for your Class Code to appear in the dropdown box.
</p>
</div>
<label>Class Screens E: </label>
<select name="ClassScreenE" id="ClassScreenE" size="5"></select>
<br>
...
</form>
</div>
<script language="javascript" type="text/javascript">
$(function(){
var count = 0;
$('p#add_field').on('click', function(){
count += 1;
$('#container').append(
'<label>ClassCode: </label>' + '<input type="text" class="autocomplete" name="ClassCode[]" id="ClassCode_' + count + '" size="34" maxlength="3">' + ' Payroll: ' + '<input type="text" name="Payroll[]" id="Payroll_' + count + '" size="10" onKeyPress="return numbersonly(this, event)">' + '<br>')
$(".autocomplete").autocomplete("scripts/findClassCode.php")
});
})
**//Edited in the following bit from Femi
//This seems to work when running 'jQuery("#ClassCode_" + i).val();' in Chrome's Inspector
//Now I need to get a solid value assigned when looping through so I can dynamically call each value to affect the a select box.
var val, i = 1, inp = jQuery("#ClassCode_" + i);
while(inp.length > 0){
// get the value
val = inp.val();
++i;
inp = jQuery("#ClassCode_" + i);
}**
</script>
</body>
</html>
All of this works perfectly. When I click the link, it generates the next set of fields while maintaining their attributes so the autocomplete piece will work. I now need to use the results of each "ClassCode_' + count + '" within the form to determine what will dynamically appear in another select box pulling data from MySQL. My issue is converting the dynamic value into a variable that can be used without having to submit the form. I've spent the day scouring the Internet to get this one working to no avail. Does anyone have any suggestions?
A little pedantic, but:
var val, i = 0, inp = jQuery("#container").find("input").find("#ClassCode_" + i);
while(inp.length > 0){
// get the value
val = inp.val();
++i;
inp = jQuery("#container").find("input").find("#ClassCode_" + i);
}
Try that?