Kendo UI + PhoneGap not working - mobile

I downloaded KENDO UI and imported /js and /css folders to my project directory. Now, I'm crreating new index.html project and referencing my all Kendo UI files in the /js and /css folders. But nothing happening. No styles, no js, nothing. Just plain HTML and nothing else. I just don't know what I'm doing wrong so I hope someone could help me with this. Here is my index.html file
<!DOCTYPE html>
<html>
<head>
<title>Where is my car?</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="js/jquery.min.js"></script>
<script src="js/kendo.mobile.min.js"></script>
<link href="styles/kendo.common.min.css" rel="stylesheet" />
<link href="styles/kendo.mobile.all.min.css" rel="stylesheet" />
</head>
<body>
<header data-role="header">
<h1>Where is my car?</h1>
</header>
<div id="content" data-role="content">
<p>asfdasfdasdfasdfasdfasdfs</p>
<a class="button" data-role="button" href="map.html?requestType=set" id="set-car-position">Set position</a>
<a class="button" data-role="button" href="map.html?requestType=get" id="find-car" data-role="button">Find car</a>
<a class="button" data-role="button" href="positions.html" id="positions-history" data-role="button">Positions history</a>
</div>
<footer data-role="footer">
<h3>Created by </h3>
<a data-icon="info" data-iconpos="notext" class="ui-btn-right">Credits</a>
</footer>
<style scoped>
#button-badge .button {
margin-left: 1em;
text-align: center;
}
#button-home .head, #facility .head, #sports .head {
display: block;
margin: 1em;
height: 120px;
-webkit-background-size: 100% auto;
background-size: 100% auto;
}
.km-ios .head, .km-blackberry .head {
-webkit-border-radius: 10px;
border-radius: 10px;
}
</style>
</body>
</html>
DEMO in jsfiddle ->> http://jsfiddle.net/ep5e8/.
Thank you for any help.
EDIT:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Where is my car?</title>
<script src="cordova.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="js/functions.js"></script>
<script src="js/maps.js"></script>
<script src="js/positions.js"></script>
<!-- Kendo UI Mobile CSS -->
<link href="styles/kendo.mobile.all.min.css" rel="stylesheet" />
<!-- jQuery JavaScript -->
<script src="js/jquery.min.js"></script>
<!-- Kendo UI Mobile combined JavaScript -->
<script src="js/kendo.mobile.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/kendo.mobile.min.js"></script>
<script src="content/shared/js/console.js"></script>
<link href="styles/kendo.common.min.css" rel="stylesheet" />
<link href="styles/kendo.mobile.all.min.css" rel="stylesheet" />
<script>
$(document).one('deviceready', initApplication);
</script>
</head>
<body>
<div id="welcome-page" data-role="view">
<header data-role="header">
<div data-role="navbar">
<span data-role="view-title">Where is my car?</span>
</div>
</header>
<div id="content" data-role="content">
<p>Where is my car? lets you bookmark where you parked your car on a map and then find a route when you want to return to it. The app will also save a log of your saved positions (up to 50).</p>
Set position
Find car
Positions history
</div>
<!--Kendo Mobile Footer -->
<footer data-role="footer">
<!-- Kendo Mobile TabStrip widget -->
<div data-role="tabstrip">
<h3>Created by</h3>
</div>
</footer>
</div>
<script>
// Initialize a new Kendo Mobile Application
var app = new kendo.mobile.Application();
</script>
</body>
</html>
positions.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Positions' history</title>
</head>
<body>
<div id="positions-page" data-role="page">
<header data-role="header">
Back
<h1>Positions' history</h1>
</header>
<div id="content" data-role="content">
<ul id="positions-list" data-role="listview" data-inset="true" data-split-icon="delete" data-filter="true">
</ul>
</div>
<footer data-role="footer">
<h3>Created by </h3>
</footer>
</div>
</body>
</html>
map.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Where is my car?</title>
<script src="cordova.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="js/functions.js"></script>
<script src="js/maps.js"></script>
<script src="js/positions.js"></script>
<!-- Kendo UI Mobile CSS -->
<link href="styles/kendo.mobile.all.min.css" rel="stylesheet" />
<!-- jQuery JavaScript -->
<script src="js/jquery.min.js"></script>
<!-- Kendo UI Mobile combined JavaScript -->
<script src="js/kendo.mobile.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/kendo.mobile.min.js"></script>
<script src="content/shared/js/console.js"></script>
<link href="styles/kendo.common.min.css" rel="stylesheet" />
<link href="styles/kendo.mobile.all.min.css" rel="stylesheet" />
<script>
$(document).one('deviceready', initApplication);
</script>
</head>
<body>
<div id="map-page" data-role="layout">
<header data-role="header">
<div data-role="navbar">
Back
<span data-role="view-title">Where is my car?</span>
</div>
</header>
<div id="content" data-role="content">
<div id="map">
</div>
</div>
</div>
<script>
// Initialize a new Kendo Mobile Application
var app = new kendo.mobile.Application();
</script>
</body>
</html>
functions.js:
function checkRequirements()
{
if (navigator.network.connection.type == Connection.NONE)
{
navigator.notification.alert(
'To use this app you must enable your internet connection',
function(){},
'Warning'
);
return false;
}
return true;
}
function updateIcons()
{
if ($(window).width() > 480)
{
$('a[data-icon], button[data-icon]').each(
function()
{
$(this).removeAttr('data-iconpos');
}
);
}
else
{
$('a[data-icon], button[data-icon]').each(
function()
{
$(this).attr('data-iconpos', 'notext');
}
);
}
}
function urlParam(name)
{
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results != null && typeof results[1] !== 'undefined')
return results[1];
else
return null;
}
/**
* Initialize the application
*/
function initApplication()
{
$('#set-car-position, #find-car').click(function() {
if (checkRequirements() === false)
{
$(this).removeClass('ui-btn-active');
return false;
}
});
$(document).on('pagebeforecreate orientationchange', updateIcons);
$('#map-page').live(
'pageshow',
function()
{
var requestType = urlParam('requestType');
var positionIndex = urlParam('index');
var geolocationOptions = {
timeout: 15 * 1000, // 15 seconds
maximumAge: 10 * 1000, // 10 seconds
enableHighAccuracy: true
};
var position = new Position();
$.mobile.loading('show');
// If the parameter requestType is 'set', the user wants to set
// his car position else he want to retrieve the position
if (requestType == 'set')
{
navigator.geolocation.getCurrentPosition(
function(location)
{
// Save the position in the history log
position.savePosition(
new Coords(
location.coords.latitude,
location.coords.longitude,
location.coords.accuracy
)
);
// Update the saved position to set the address name
Map.requestLocation(location);
Map.displayMap(location, null);
navigator.notification.alert(
'Your position has been saved',
function(){},
'Info'
);
},
function(error)
{
navigator.notification.alert(
'Unable to retrieve your position. Is your GPS enabled?',
function(){
alert("Unable to retrieve the position: " + error.message);
},
'Error'
);
$.mobile.changePage('index.html');
},
geolocationOptions
);
}
else
{
if (position.getPositions().length == 0)
{
navigator.notification.alert(
'You have not set a position',
function(){},
'Error'
);
$.mobile.changePage('index.html');
return false;
}
else
{
navigator.geolocation.watchPosition(
function(location)
{
// If positionIndex parameter isn't set, the user wants to retrieve
// the last saved position. Otherwise he accessed the map page
// from the history page, so he wants to see an old position
if (positionIndex == undefined)
Map.displayMap(location, position.getPositions()[0]);
else
Map.displayMap(location, position.getPositions()[positionIndex]);
},
function(error)
{
console.log("Unable to retrieve the position: " + error.message);
},
geolocationOptions
);
}
}
}
);
$('#positions-page').live(
'pageinit',
function()
{
createPositionsHistoryList('positions-list', (new Position()).getPositions());
}
);
}
/**
* Create the positions' history list
*/
function createPositionsHistoryList(idElement, positions)
{
if (positions == null || positions.length == 0)
return;
$('#' + idElement).empty();
var $listElement, $linkElement, dateTime;
for(var i = 0; i < positions.length; i++)
{
$listElement = $('<li>');
$linkElement = $('<a>');
$linkElement
.attr('href', '#')
.click(
function()
{
if (checkRequirements() === false)
return false;
$.mobile.changePage(
'map.html',
{
data: {
requestType: 'get',
index: $(this).closest('li').index()
}
}
);
}
);
if (positions[i].address == '' || positions[i].address == null)
$linkElement.text('Address not found');
else
$linkElement.text(positions[i].address);
dateTime = new Date(positions[i].datetime);
$linkElement.text(
$linkElement.text() + ' # ' +
dateTime.toLocaleDateString() + ' ' +
dateTime.toLocaleTimeString()
);
// Append the link to the <li> element
$listElement.append($linkElement);
$linkElement = $('<a>');
$linkElement.attr('href', '#')
.text('Delete')
.click(
function()
{
var position = new Position();
var oldLenght = position.getPositions().length;
var $parentUl = $(this).closest('ul');
position.deletePosition($(this).closest('li').index());
if (oldLenght == position.getPositions().length + 1)
{
$(this).closest('li').remove();
$parentUl.listview('refresh');
}
else
{
navigator.notification.alert(
'Position not deleted. Something gone wrong so please try again.',
function(){},
'Error'
);
}
}
);
// Append the link to the <li> element
$listElement.append($linkElement);
// Append the <li> element to the <ul> element
$('#' + idElement).append($listElement);
}
$('#' + idElement).listview('refresh');
}
maps.js:
function Map()
{
}
/**
* Display the map showing the user position or the latter and the car position
*/
Map.displayMap = function(userPosition, carPosition)
{
var userLatLng = null;
var carLatLng = null;
if (userPosition != null)
userLatLng = new google.maps.LatLng(userPosition.coords.latitude, userPosition.coords.longitude);
if (carPosition != null)
carLatLng = new google.maps.LatLng(carPosition.position.latitude, carPosition.position.longitude);
var options = {
zoom: 20,
disableDefaultUI: true,
streetViewControl: true,
center: userLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map'), options);
var marker = new google.maps.Marker({
position: userLatLng,
map: map,
title: 'Your position'
});
// If carLatLng is null means that the function has been called when the
// user set his current position and that is when he parked the car so the
// icon will be shown accordingly.
if (carLatLng == null)
marker.setIcon('images/car-marker.png');
else
marker.setIcon('images/user-marker.png');
var circle = new google.maps.Circle({
center: userLatLng,
radius: userPosition.coords.accuracy,
map: map,
fillColor: '#70E7FF',
fillOpacity: 0.2,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
map.fitBounds(circle.getBounds());
if (carLatLng != null)
{
marker = new google.maps.Marker({
position: carLatLng,
map: map,
icon: 'images/car-marker.png',
title: 'Car position'
});
circle = new google.maps.Circle({
center: carLatLng,
radius: carPosition.position.accuracy,
map: map,
fillColor: '#70E7FF',
fillOpacity: 0.2,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
// Display route to the car
options = {
suppressMarkers: true,
map: map,
preserveViewport: true
}
this.setRoute(new google.maps.DirectionsRenderer(options), userLatLng, carLatLng);
}
$.mobile.loading('hide');
}
/**
* Calculate the route from the user to his car
*/
Map.setRoute = function(directionsDisplay, userLatLng, carLatLng)
{
var directionsService = new google.maps.DirectionsService();
var request = {
origin: userLatLng,
destination: carLatLng,
travelMode: google.maps.DirectionsTravelMode.WALKING,
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(
request,
function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
directionsDisplay.setDirections(response);
else
{
navigator.notification.alert(
'Unable to retrieve a route to your car. However, you can still find it by your own.',
function(){},
'Warning'
);
}
}
);
}
/**
* Request the address of the retrieved location
*/
Map.requestLocation = function(position)
{
new google.maps.Geocoder().geocode(
{
'location': new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
},
function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var positions = new Position();
positions.updatePosition(0, positions.getPositions()[0].coords, results[0].formatted_address);
}
}
);
}
positions.js
function Position(position, address, datetime)
{
var _db = window.localStorage;
var MAX_POSITIONS = 50;
this.position = position;
this.address = address;
this.datetime = datetime;
this.getMaxPositions = function()
{
return MAX_POSITIONS;
}
this.savePosition = function(position, address)
{
if (!_db)
{
console.log('The database is null. Unable to save position');
navigator.notification.alert(
'Unable to save position',
function(){},
'Error'
);
}
var positions = this.getPositions();
if (positions == null)
positions = [];
positions.unshift(new Position(position, address, new Date()));
// Only the top MAX_POSITIONS results are needed
if (positions.length > this.MAX_POSITIONS)
positions = positions.slice(0, this.MAX_POSITIONS);
_db.setItem('positions', JSON.stringify(positions));
return positions;
}
this.updatePosition = function(index, position, address)
{
if (!_db)
{
console.log('The database is null. Unable to update position');
navigator.notification.alert(
'Unable to update position',
function(){},
'Error'
);
}
var positions = this.getPositions();
if (positions != null && positions[index] != undefined)
{
positions[index].coords = position;
positions[index].address = address;
}
_db.setItem('positions', JSON.stringify(positions));
return positions;
}
this.deletePosition = function(index)
{
if (!_db)
{
console.log('The database is null. Unable to delete position');
navigator.notification.alert(
'Unable to delete position',
function(){},
'Error'
);
}
var positions = this.getPositions();
if (positions != null && positions[index] != undefined)
positions.splice(index, 1);
_db.setItem('positions', JSON.stringify(positions));
return positions;
}
this.getPositions = function()
{
if (!_db)
{
console.log('The database is null. Unable to retrieve positions');
navigator.notification.alert(
'Unable to retrieve positions',
function(){},
'Error'
);
}
var positions = JSON.parse(_db.getItem('positions'));
if (positions == null)
positions = [];
return positions;
}
}
function Coords(latitude, longitude, accuracy)
{
this.latitude = latitude;
this.longitude = longitude;
this.accuracy = accuracy;
}
style.css:
.ui-header .ui-title,
.ui-footer .ui-title,
.ui-btn-inner *
{
white-space: normal !important;
}
.photo
{
display: block;
margin: 0px auto;
}
dl.informations dt
{
font-weight: bold;
}
#map
{
width: 100%;
height: 600px;
}
Sorry for this amount of code, but I just can't convert a design and functionality from jQM to KendoUI Mobile.

Kendo initialization
You are missing the code bits that let kendo do its magic. I am assuming that you are using Kendo UI Mobile.
The following should be inserted before your closing body tag.
<script>
// Initialize a new Kendo Mobile Application
var app = new kendo.mobile.Application();
</script>
You can read the following doc with more related details:
http://docs.kendoui.com/getting-started/introduction
Kendo Views
Also I noticed that you are not using any view. I am not sure what you want to achieve but tipically when using Kendo you should have a view that wraps the header, content and footer code.
View documentation: http://docs.kendoui.com/getting-started/mobile/view
I suggest reading the documentation stated above (if you haven´t already do so) and to try the examples first, and then start writing your code.
Snippet
<!-- Kendo Mobile View -->
<div data-role="view" data-title="View" id="index">
<!--Kendo Mobile Header -->
On the other hand, it is difficult to check the full code working as it should be in the jsfiddle as you are not linking or copy pasting the CSS and JS files that you are stating in the code.
EDIT
Regarding data source
I just skimmed your code but It seems you are not using the Kendo DataSource.
Read the following document which explains how to bind data to your controls.
http://docs.kendoui.com/howto/use-the-datasource-component
http://docs.kendoui.com/getting-started/data-attribute-initialization
Bear in mind that jQM and Kendo UI mobile have very different approaches. Kendo uses a Model View ViewModel (MVVM) so a bit of work should be required to move the jquery - jQM code to Kendo, it is basically a matters of structure.
Again, before start playing with Kendo I strongly recommend reading the documentation. You could think you are wasting time, however reading the doc will save you tons of time and headaches.

Related

File drag and drop functionality in Angular js/MVC not working

I am trying to implement a simple file drag and drop functionality in Angular js/MVC.
I created a directive for the drag and drop.
(function (angular, undefined) {
'use strict';
angular.module('fileupload', [])
.directive("myDirective", function ($parse) {
return {
restrict: 'A',
link: fileDropzoneLink
};
function fileDropzoneLink(scope, element, attrs) {
element.bind('dragover', processDragOverOrEnter);
element.bind('dragenter', processDragOverOrEnter);
element.bind('dragend', endDragOver);
element.bind('dragleave', endDragOver);
element.bind('drop', dropHandler);
var onImageDrop = $parse(attrs.onImageDrop);
//When a file is dropped
var loadFile = function (files) {
scope.uploadedFiles = files;
scope.$apply(onImageDrop(scope));
};
function dropHandler(angularEvent) {
var event = angularEvent.originalEvent || angularEvent;
var files = event.dataTransfer.files;
event.preventDefault();
loadFile(files)
}
function processDragOverOrEnter(angularEvent) {
var event = angularEvent.originalEvent || angularEvent;
if (event) {
event.preventDefault();
}
event.dataTransfer.effectAllowed = 'copy';
element.addClass('dragging');
return false;
}
function endDragOver() {
element.removeClass('dragging');
}
}
});
}(angular));
This is the template
<div class="dropzone" data-my-Directive on-image-drop="$ctrl.fileDropped()">
Drag and drop pdf files here
</div>
This is my component code
(function (angular, undefined) {
'use strict';
angular.module('test', [])
.component('contactUs', contactUs());
function contactUs() {
ContactUs.$inject = ['$scope', '$http'];
function ContactUs($scope, $http) {
var ctrl = this;
ctrl.files = [];
ctrl.services = {
$scope: $scope,
$http: $http,
};
}
//file dropped
ContactUs.prototype.fileDropped = function () {
var ctrl = this;
var files = ctrl.services.$scope.uploadedFiles;
angular.forEach(files, function (file, key) {
ctrl.files.push(file);
});
}
return {
controller: ContactUs,
templateUrl: 'partials/home/contactus/'
};
}
}(angular));
Sometimes the drag and drop works absolutely fine without any issue. But some times I get the below issue and the drag and drop does not work and I get the black invalid cursor.
This issue is random and i do not see any errors in the console.
And I also tried other third party components like angular-file-upload
https://github.com/nervgh/angular-file-upload and I am seeing the exact same issue with that component also.
EDIT :
Answer updated for pdf preview. The code is available in the same plunker.
References : Excellent solution by #Michael at https://stackoverflow.com/a/21732039/6347317
In the example above, the response from the http POST is used in "new Blob([response]". In angular-file-upload library, the "response" would be "fileItem._file" property in "uploader.onAfterAddingFile" function. You can console log to check the data these have , so as to understand it better.
Also please note that if PDf viewer is not enabled in chrome, it has to be enabled using this: https://support.google.com/chrome/answer/6213030?hl=en
END EDIT
Since you mentioned that you tried with angular-file-upload library, i have created a plunker with it:
http://plnkr.co/edit/jeYg5fIRaC9wuEYSNOux?p=info
HTML:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-file-upload/2.5.0/angular-file-upload.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div class="col-sm-4">
<h3>Select files</h3>
<div ng-show="uploader.isHTML5">
<!-- 3. nv-file-over uploader="link" over-class="className" -->
<div class="well my-drop-zone" style="width:300px" nv-file-drop nv-file-over="" uploader="uploader"
filters="syncFilter">
<label>
Click here or Drag and Drop file
<input type="file" style="visibility:hidden;" nv-file-select nv-file-over="" uploader="uploader"
filters="syncFilter" multiple/>
</label>
<div class="progress" style="margin-bottom: 0;">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': uploader.queue[0].progress + '%' }"></div>
</div>
<div>{{uploader.queue[0].file.name}}</div>
<div ng-show="showAlert" class="alert alert-warning alert-dismissable">
×
<strong>Clear the existing file before uploading again!!</strong>
</div>
</div>
</div>
</div>
</body>
</html>
JS:
var app = angular.module('plunker', ['angularFileUpload']);
app.controller('MainCtrl', function($scope,FileUploader) {
var uploader = $scope.uploader = new FileUploader();
// FILTERS
// a sync filter
uploader.filters.push({
name: 'syncFilter',
fn: function(item /*{File|FileLikeObject}*/, options) {
console.log('syncFilter' + this.queue.length);
return this.queue.length < 1;
}
});
// an async filter
uploader.filters.push({
name: 'asyncFilter',
fn: function(item /*{File|FileLikeObject}*/, options, deferred) {
console.log('asyncFilter');
setTimeout(deferred.resolve, 1e3);
}
});
uploader.allowNewFiles = true;
uploader.filters.push({
name:'csvfilter',
fn: function() {
return this.allowNewFiles;
}
});
// CALLBACKS
uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
console.info('onWhenAddingFileFailed', item, filter, options);
$scope.showAlert=true;
};
uploader.onAfterAddingFile = function(fileItem) {
};
});
It is pretty straight forward and i dont get the error you mentioned. We are actually using this library in one of our Projects. I have also added a filter to restrict upload to only 1 file.
Please check this and let me know how it goes or if you have any doubts in the code.

How can I take a user input (youtube video link) and embed it as an iframe using React.js?

I am currently trying to develop a web app that can take a user input (ie. YouTube™ video url) and output an iframe of that video. I was able to produce this result with basic HTML and JavaScript but now that I have to convert this to React I cannot figure out what am I doing wrong.
Here is some relevant code.
app.js
var React = require('react');
var ReactDOM = require('react-dom');
var Header = React.createClass({
render: function () {
return (
<header>
<h1>{this.props.title}</h1>
</header>
);
}
});
var createIframeLink = function (link) {
if (link.charAt(12) == 'y') { //if the 13th character = y (youtube videos)
var number = link.substring(32); //key # = from 33rd character on
var embed = "https://www.youtube.com/embed/" + number; //Add youtube link before key #
return embed
}
else if (link.charAt(12) == 'o') { //if the 13th character = o (vimeo videos)
var number = link.substring(18); //key # = from 19th character on
var embed = "https://player.vimeo.com/video/" + number; //Add vimeo link before key #
return embed
}
else {}
};
var iframevideo = React.createClass({
render: function() {
return (
<div id="iframe">
<iframe id="iframe" src="this.props.embed" frameborder="0"></iframe>
</div>
)
}
});
var iframeblock = React.createClass({
render: function() {
var link = this.state.link;
return (
<div className="form">
<div>
<label>Principal:</label>
<input type="text" value={this.state.link} onChange={this.createIframeLink}/>
</div>
</div>
<iframe id="iframe" src="this.props.embed" frameborder="0"></iframe>
)
}
});
var App = React.createClass({
render: function () {
return (
<div>
<Header title="Vidvision"/>
<iframeblock/>
</div>
);
}
});
ReactDOM.render(<App/>, document.getElementById("app"));
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href='http://fonts.googleapis.com/css?family=Roboto:400,300,700' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="app"></div>
<script src="build/app.bundle.js"></script>
</body>
</html>
When I run my app I am getting an error:
(SyntaxError: ... Adjacent JSX elements must be wrapped in an enclosing tag (48:12).
Here is the plain HTML and JavaScript code that works:
<div class="myIframe">
<iframe id="iframe" src="" frameborder="0" &fs=0></iframe>
</div>
<script type="text/javascript">
function createYouTubeEmbedLink (link) {
link = document.getElementById('link').value;
if (link.charAt(12) == 'y') { //if the 13th character = y (youtube videos)
var number = link.substring(32); //key # = from 33rd character on
var embed = "https://www.youtube.com/embed/" + number; //Add youtube link before key #
document.getElementById('iframe').src = embed;
}
else if (link.charAt(12) == 'o') { //if the 13th character = o (vimeo videos)
var number = link.substring(18); //key # = from 19th character on
var embed = "https://player.vimeo.com/video/" + number; //Add vimeo link before key #
document.getElementById('iframe').src = embed;
}
else {}
}
</script>
The error you're getting is because your Component iframeblock cannot return two elements, so you need to wrap the <div> and the <iframe> inside another <div>
var iframeblock = React.createClass({
render: function() {
var link = this.state.link;
return (
<div>
<div className="form">
<div>
<label>Principal:</label>
<input type="text" value={this.state.link} onChange={this.createIframeLink}/>
</div>
</div>
<iframe id="iframe" src="this.props.embed" frameborder="0"></iframe>
</div>
);
}
});

a simple SPA example in backbone

I have a little problem in configuring the mistake in my code.
I have written index.html which includes the template, and a jscript file which includes the model, collection and view.
please let me know where i am doing wrong. I particularly doubt whether i am using el tag wrongly.. or is it wrong in fetching the json data or in render function.
index.php
<head>
<meta charset="utf-8">
<title>Backbone.js News List</title>
<link rel="stylesheet" href="newsList.css"/>
</head>
<body>
<script src="../../test/vendor/json2.js"></script>
<script src="../../test/vendor/jquery.js"></script>
<script src="../../test/vendor/underscore.js"></script>
<script src="../../backbone.js"></script>
<script src="newsList.js"></script>
<header>
<h1 id="center_text">News List</h1>
</header>
<h2>News Trending</h2>
<div id="news-list"></div>
<div id="footer">
<h3 id="center_text" >Copy Right</h3>
</div>
<!-- Templates -->
<script type="text/template" id="item-template">
<div class="container" id="news">
<img id="img" src = <%- img %> >
<section>
<b id="title" ><%- title %> </b>
<br><%- snippet %>
<p><small id ="date"> <%- date%> </small></p>
</section>
</div>
</script>
</body>
</html>
JavaScript code
newsList.js
$(function(){
var NewsList = Backbone.Model.extend({
// Default attributes for the todo item.
defaults: {
id:"",
title: "empty NewsList...",
img:"",
snippet:"",
date:""
},
initialize: function(){
console.log("model initialized");
}
});
var NewsListColln = Backbone.Collection.extend({
// Reference to this collection's model.
model: NewsList,
url: 'http://api.divum.in/training/json/newslist.php',
initialize: function(){
console.log("colln initialized");
}
});
//VIEW
// The DOM element for a news item...
var NewsListView = Backbone.View.extend({
//... is a list tag.
el:"#news-list",
template: _.template($('#item-template').html()),
initialize: function() {
console.log("in view");
this.render;
},
render: function(eventName) {
console.log("in render");
var n = newsLists.content;
$.each(n.news, function(newslist){
var newsTemplate= this.template(newslist.toJson());
$(this.el).append(newsTemplate);
}, this);
return this;
}
});
var AppView = Backbone.View.extend({
el: "body",
initialize: function() {
var newsLists = new NewsListcolln();
var newsView = new NewsListView({model: newsLists});
newsLists.bind('reset', function () { newsView.render();});
newsLists.fetch();
}
});
var App = new AppView();
/* var newsLists = new NewsListColln;
var newsListView = new NewsListView({model: newsLists});
newsLists.fetch({ url: "http://api.divum.in/training/json/newslist.php", success: function() {
console.log(newsLists);
}});
newsLists.bind('reset', function () { newsListView.render(); });*/
/*
render:function(){
this.$("news-list").append(newsView.render().el);
}*/
});
css-- newsList.css file
body {
padding:0px;
margin: 0px;
background-color: black;
color:white;
}
h1 {
padding:5px;
margin: 0;
background-color: #FFFF00;
color:black;`enter code here`
}
h3{
margin: 0;
background-color:#FFFF00;
color:black;
}
h2{
padding:5px;
margin:0px;
background-color: white;
color:black;
}
.container {
color:white;
}
div img {
float: left;
width: 128px;
height:: 85%;
}
.container section{
margin-left:128px;
}
#footer{
position: fixed;
width: 100%;
bottom: 0px;
}
#center_text{
text-align:center;
}
#left_text{
text-align:left;
}
div p{
text-align: right;
}
.clearfix{
overflow: auto;
}
Errors:
The site returns a object, but collections are arrays. You need to use the models in this case.
render is a function, so you have to call it: this.render();
After passing a model to a view, access it via this.model.
A model needs either a url or a urlRoot set if you want to fetch it seperately
fetch is asynchronous you have to wait until it finishes.
Use .get() to access model properties
Working code: http://jsfiddle.net/FHsrL/1/

How do i get multiple values from a popup window then insert it in the database

im new here so could anyone help me. im trying to make a document tracking system and im having problems in getting multiple values from a popup window then inserting them in the database table so that the only people who could access those documents are those on the inserted list. can anyone help me please?? >_< newbie
Here is part of my code -- when i click it it selects from a listbox in a popupwindow.
<html>
<input id = 'input2' type="button" value="Select Route" onclick="SelectName()" />
<script type="text/javascript">
var popup;
function SelectName() {
popup = window.open("offices.php", "Popup", "width=500,height=500");
popup.focus();
}
</script>
</html>
here is the Popup_info--
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<html>
<head>
<title>Select offices</title>
<link rel="stylesheet" href="styles.css" type="text/css">
<script type="text/javascript">
function select(){
var str='';
for (i=0;i<s1.length;i++) {
if(s1[i].selected){
str +=s1[i].value+ " ";
}
}
document.getElementById("msg3").innerHTML=str;
return true;
}
function select_all(){
var str='';
for (i=0;i<s1.length;i++) {
s1[i].selected=true
{
str +=s1[i].value+ " ";
}
}
document.getElementById("msg3").innerHTML=str;
}
function deselect_all(){
var str='';
for (i=0;i<s1.length;i++) {
s1[i].selected=false
{
str ="";
}
}
document.getElementById("msg3").innerHTML=str;
}
</script>
</head>
<body>
<br>
<br>
<center>
<p> Select the Document Route.</p>
<p> Hold ctrl for multiple Selection.</p>
<?php include ('db.php');
$data = mysql_query("select office from office_table");
echo "<select name = no_year id= s1 onChange='select()'; required multiple size= 10 value ='' width='200' style='width: 200px' > ";
while($row=mysql_fetch_assoc($data))
{
echo "<option> ".$row['office']."
</option>";
}
echo "</select>";
?>
<div id='msg3' width = 300> <table ></table></div>
</body>
<br><br><br><br>
<input type='button' value='Select All' onclick='select_all();' id = 'input2' />
<input type='button' value='Clear' onclick='deselect_all();' id = 'input2' />
<input type="button" value="Submit" onclick="Set_select();" id = 'input2' />
<script type="text/javascript">
function Set_select() {
if (window.opener != null && !window.opener.closed) {
var txtName = window.opener.document.getElementById("txtName");
txtName.value = document.getElementById("msg3").innerHTML;
}
window.close();
}
</script>
</html>
I'm just new on php and i want to insert the data i get here into the table specifically. i mean by each click its a separated data when inserted. please help.

Autocomplete google map api use to find postal code only by addresspicker

I want to search postal code using address,city etc by auto complete Google API .
I am using code like this .it is providing all location and place details but i need only postal ,if there is any suggestion then please provide.
<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes /base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://xilinus.com/jquery-addresspicker/src/jquery.ui.addresspicker.js">
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style type="text/css">
#map {
border: 1px solid #DDD;
width:300px;
height: 300px;
float:left;
margin: 0px 0 0 10px;
-webkit-box-shadow: #AAA 0px 0px 15px;
}
div {
font-family: Arial;
font-size: 10pt;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
var geocoder = new google.maps.Geocoder();
$("#addresspicker").autocomplete({
source: function (request, response) {
geocoder.geocode({ address: request.term }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
response($.map(results, function(result) {
if ($.inArray("street_address", result.types) >= 0) {
return result.formatted_address;
}
}));
}
});
},
select: function (event, ui) {
var parts = ui.item.label.split(",")
, address1 = parts[0]
, address2 = parts.slice(1).join(",").trim();
$("#postal").val(address1 + "\n" + address2);
}
});
});
$(function() {
var addresspicker = $("#addresspicker").addresspicker();
var addresspickerMap = $( "#addresspicker_map" ).addresspicker({
elements: {
map: "#map",
lat: "#lat",
lng: "#lng",
locality: '#locality',
country: '#country'
}
});
var gmarker = addresspickerMap.addresspicker( "marker");
gmarker.setVisible(true);
addresspickerMap.addresspicker( "updatePosition");
});
</script>
</head>
<body>
<div>
<label>Address : </label><input id="addresspicker" />
</div>
<br/>
<br/>
<div>
<div>
<label>Address : </label> <input id="addresspicker_map" /> <br/>
<label>Locality: </label> <input id="locality" disabled=disabled> <br/>
<label>Country: </label> <input id="country" disabled=disabled> <br/>
<label>Latitude: </label> <input id="lat" disabled=disabled> <br/>
<label>Longitude: </label> <input id="lng" disabled=disabled> <br/>
<label>postal: </label> <input id="postal" disabled=disabled> <br/>
</div>
<br/>
<div id="map"></div>
</div>
</body>
</html>
Thanks in advance.......
I haven't used jquery.ui.addresspicker but you may find this usefull
You can use the autocomplete.getPlace(); function to get a JSON object that "can" contain post code dependent on the search query.
I'll try keep this vanilla JS
The docs here explain it well
https://developers.google.com/places/documentation/autocomplete
// autocomplete search restriction (if required)
var options = {
types: ['(regions)'],
componentRestrictions: { country: "au" }
}
// create you autocomplete feild
var input = (document.getElementById('addresspicker'));
var autocomplete = new google.maps.places.Autocomplete(input, options);
var infowindow = new google.maps.InfoWindow();
// fired when an autocomplete option is selected or the input is submitted
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
// pull out the data you need
...
});
I have some validation function i wrote for this as well. If you need more help, comment and i will add links.
I have the same prob.
The PlaceResult objet returned when calling getPlace() doesnt automatically contains a Zipcode, and when it does, its in the "administrative_area_level_2" field.
I'm now heading on calling the main gmap geocoding service in order to get the zipcode associated to the chosen city.
I created a method called get postal code, that extracts the postal code from the result provided by address picker.
Basic setup of addresspicker and calling the function with the address components.
addressPicker.bindDefaultTypeaheadEvent($('#addresssearch'));
$(addressPicker).on('addresspicker:selected', function (event, result) {
var postal_code = getPostalcode(result.placeResult.address_components);
});
Function that extracts postal_code from address components.
function getPostalcode(address_components) {
for(var i = 0; i < address_components.length; i++){
if (address_components[i]['types'].includes("postal_code")) {
var final_value = address_components[i]['long_name'];
}
}
return final_value || ''
}
If no postal code available, it would return empty string.

Resources