On adding ko validation extender to dynamic objects it is not displaying the error message when showAllMessages() is called. There is also no span tag added below the respective controls which will show the error message.
I also like to show the error message just below the control as soon as the object is added to observable array.
Please find the fiddle
http://plnkr.co/edit/PUgxqrarDeaabDxUwgLO?p=preview
JavaScript
var schedule = function() {
var self = this;
self.name = ko.observable();
self.startDate = ko.observable();
self.endDate = ko.observable();
// Add validation
self.name.extend({required: {message: 'Name Required'}});
self.startDate.extend({required: {message: 'Start Date Required'}});
self.endDate.extend({required: {message: 'End Date Required'}});
}
var viewmodel = {
model: {
lookups: {
grandSlams: ["Australian Open", "French Open", "Wimbledon", "US Open"]
},
schedules: ko.observableArray(),
status: ko.observable()
},
actions: {
addSchedule: function() {
console.log('Add Called');
viewmodel.model.schedules.push(new schedule());
viewmodel.model.status('Edited');
console.log(viewmodel.model.schedules().length);
},
saveSchedule: function(){
console.log('Save Called');
var errors = ko.validation.group(viewmodel.model.schedules, { deep: true });
if (errors().length > 0) {
console.log(errors());
errors.showAllMessages();
hasError = true;
}
viewmodel.model.status('Saved!!!');
}
}
};
$(function() {
ko.validation.init({
insertMessages: true,
messagesOnModified: true,
grouping: {
deep: true, //by default grouping is shallow
observable: true //and using observables
}
});
ko.applyBindings(viewmodel);
});
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script data-require="knockout#2.2.1" data-semver="2.2.1" src="//cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min.js"></script>
<script data-require="knockout-validation#*" data-semver="1.0.2" src="//cdnjs.cloudflare.com/ajax/libs/knockout-validation/1.0.2/knockout.validation.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Knockout Validation!</h1>
<button data-bind="click: actions.addSchedule">Add Schedule</button>
<button data-bind="click: actions.saveSchedule">Save Schedule</button>
<h3>Schedules</h3>
<table>
<thead>
<tr>
<th>Grand Slams</th>
<th>Start</th>
<th>End</th>
</tr>
</thead>
<tbody data-bind="foreach:model.schedules">
<tr>
<td style="width:250px">
<select data-bind="options: $root.model.lookups.grandSlams, optionsCaption:'Select...'"></select>
</td>
<td style="width:250px">
<input type="text" data-bind="value: startDate" />
</td>
<td style="width:250px">
<input type="text" data-bind="value: endDate" />
</td>
</tr>
</tbody>
</table>
<h3 data-bind="text: model.status"></h3>
</body>
</html>
Updated example
You're missing the value binding on the select element. It should be
<select data-bind="value: name, options: $root.model.lookups.grandSlams, optionsCaption:'Select...'"></select>
Updated viewmodel if you want to validate on addSchedule (you can probably remove this.actions.showErrors() from save now, I left it just in case)
var viewmodel = {
model: {
lookups: {
grandSlams: ["Australian Open", "French Open", "Wimbledon", "US Open"]
},
schedules: ko.observableArray(),
status: ko.observable()
},
actions: {
addSchedule: function() {
console.log('Add Called');
viewmodel.model.schedules.push(new schedule());
viewmodel.model.status('Edited');
this.actions.showErrors();
console.log(viewmodel.model.schedules().length);
},
showErrors: function() {
var errors = ko.validation.group(viewmodel.model.schedules, { deep: true });
if (errors().length > 0) {
console.log(errors());
errors.showAllMessages();
hasError = true;
}
},
saveSchedule: function(){
console.log('Save Called');
var errors = ko.validation.group(viewmodel.model.schedules, { deep: true });
this.actions.showErrors();
viewmodel.model.status('Saved!!!');
}
}
};
Related
I have a table (list) on my front end in html, and foreach row, I have a button:
...
<td>
<button data-bind="click: sendDataToApi">Test button</button>
</td>
...
and in the .js file I have something like this:
define(['viewmodels/shell', 'durandal/services/logger', 'plugins/dialog', 'viewmodels/shell', 'toastr', 'knockout', 'kovalidationconfig', 'plugins/router', 'typeahead.bundle'],
function (shell, logger, dialog, shell, toastr, ko, kvc, router, typeahead) {
var vm = {
activate: activate,
shell: shell,
data: ko.observableArray([]),
close: function () {
$(window).off('popstate', vm.goBack);
$(window).off('resize', adjustModalPosition);
dialog.close(vm, 'cancel');
},
goBack: function () {
$(window).off('popstate', vm.goBack);
$(window).off('resize', adjustModalPosition);
dialog.close(vm, 'back');
},
editPreregisteredChildren: function () {
router.navigate("#/function/" + this.id);
},
currentPage: ko.observable(1),
itemsPerPage: ko.observable(10),
hasNextPage: ko.observable(false),
previousPage: previousPage,
nextPage: nextPage,
sendDataToApi: function () {console.log("sdsdsds")},
searchCriteria: ko.observable(''),
applySearch: applySearch,
locations: ko.observableArray([]),
locationId: ko.observable(),
LocationName: ko.observable(),
exportHref: ko.observable("/spa/ExportSchedulings"),
bindingComplete: function (view) {
bindFindLocationEvent(view);
}
};
function sendDataToApi() {
console.log("hello.")
};
});
so, firstly, I want to get console.log("something") to work.
for now Im getting error in my console in chrome:
Uncaught ReferenceError: Unable to process binding "click: function(){return sendDataToApi }"
Message: sendDataToApi is not defined
I dont get it why?
after that I need to do an ajax call to my controller, and the end to call some api in that controller, and return the information if the api call was successfull or not.
I am going to assume that you are trying to display information in a table given the
<td>
<button data-bind="click: sendDataToApi">Test button</button>
</td>
I am also going to assume that that there is a ko:foreach at the table or table-body level. if that is the case then sendDataToApi is associated with the parent vm object and not the object that is currently being used to create the table rows.
If that is the case then you would need to use the $parent.sendDataToApi or $root.sendDataToApi
<td>
<button data-bind="click: $parent.sendDataToApi">Test button</button>
</td>
or
<td>
<button data-bind="click: $root.sendDataToApi">Test button</button>
</td>
EDIT
you just need to add a parameter to the receiving function because the knockout passes the current object.
var serverData = [{
id: 1,
name: 'Test 1'
},
{
id: 2,
name: 'Test 2'
},
{
id: 3,
name: 'Test 3'
},
];
function ViewModel() {
var self = this;
self.data = ko.observableArray([]);
self.checkServer = function checkServer(row) {
console.log(ko.toJS(row));
}
self.fillTable = function fillTable() {
var mappedData = serverData.map(r => new RowViewModel(r));
self.data(mappedData);
}
}
function RowViewModel(data) {
var self = this;
self.id = ko.observable(data.id || 0);
self.name = ko.observable(data.name || '');
}
ko.applyBindings(new ViewModel());
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<button class="button" data-bind="click: fillTable">Fill Table</button>
<table class="table">
<tbody data-bind="foreach: data">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
<td>
<button data-bind="click: $parent.checkServer">Check Server</button>
</td>
</tr>
</tbody>
</table>
I am new to react and trying to build a table component that changes based on what is passed in for headers and rows.
I have been following the fb react tutorials and I have hit a road block I have looked on here and did some changes but nothing is working.
Here is my HTML page that gets the generated content.
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=10; IE=9; IE=8; IE=7; IE=EDGE" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" type="text/css" href="/vendor/twbs/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/vendor/etdsolutions/sweetalert/sweetalert.css?<?= assetCacheQueryStr() ?>" />
<link rel="stylesheet" type="text/css" href="/lib/jquery-ui-1.11.4/jquery-ui.css">
<link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.9.3/css/bootstrap-select.min.css">
<!-- Javascript -->
<script src="https://unpkg.com/react#15.3.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15.3.2/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-core#5.8.38/browser.min.js"></script>
<script src="https://unpkg.com/jquery#3.1.0/dist/jquery.min.js"></script>
<script src="https://unpkg.com/remarkable#1.6.2/dist/remarkable.min.js"></script>
<script src="/vendor/etdsolutions/sweetalert/sweetalert.min.js?<?= assetCacheQueryStr()?>"></script>
<script src="/vendor/twbs/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.9.3/js/bootstrap-select.min.js"></script>
<script src="/lib/sorttable.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<title>React</title>
</head>
<body>
<div id="loadboardContainer"></div>
<!-- Import the table react setup. -->
<script type="text/babel" src="test.js"></script>
</body>
</html>
Now I have the external react script in the test.js file which is this.
var Table = React.createClass({
getInitialState: function() {
return {
results: [],
columns: []
}
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function(result) {
result = JSON.parse(result);
this.setState({
results: result['resultRows'],
columns: $.makeArray(result['resultCols'])
});
}.bind(this));
},
componentWillUnmount: function(){
this.serverRequest.abort();
},
render: function() {
// Set array for rows.
var rows = [];
var header = [];
this.state.columns.map(function(cols) {
header.push(<TableColumns data={cols.cols} key={cols.id} />);
});
this.state.results.map(function(result) {
rows.push(<TableRow data={result.rows} key={result.id} />);
});
// Loop through head to get columns.
/*this.props.columns.forEach(function(cols) {
header.push(<TableColumns data={cols.cols} key={cols.id} />);
});
// Loop through the returned rows and display.
this.props.results.forEach(function(result) {
rows.push(<TableRow data={result.rows} key={result.id} />);
});*/
// Return the table.
return (
<table className="table table-condensed">
<thead>
{header}
</thead>
<tbody>
{rows}
</tbody>
</table>
);
}
});
// Set up columns
var TableColumns = React.createClass({
render: function() {
var colNodes = this.props.data.map(function(col, i){
return (
<th key={i}>{col}</th>
);
});
return (
<tr>
{colNodes}
</tr>
);
}
});
// Set up row
var TableRow = React.createClass({
render: function() {
var rowNodes = this.props.data.map(function(row, i){
return (
<td key={i}>{row}</td>
);
});
return (
<tr>
{rowNodes}
</tr>
);
}
});
var futureContainer = document.getElementById('loadboardContainer');
ReactDOM.render(<Table source="getTableValues.php" />, futureContainer);
As you can see I have the commented out part of what used to be the props calls to the table. Now that I am trying to get the information from another file it looks like on here I have to use state.
On the other file this is what I have. Its just an array of array to return data before I actually query the stuff.
<?php
// Start the session.
session_start();
// Set Variables.
$returned = array(); // Returns results
$returned['resultRows'][0] = array();
$returned['resultRows'][0]['id'] = 10221;
$returned['resultRows'][0]['rows'] = array("654221", "2016-03-26", "Customer 1", "98755/54622", "Carrier 1", "Driver 1", "2016-03-28", "TX - IN", "DRY", "1240", "", "", "This is a test note");
$returned['resultRows'][1] = array();
$returned['resultRows'][1]['id'] = 10223;
$returned['resultRows'][1]['rows'] = array("654221", "2016-03-26", "Customer 1", "98755/54622", "Carrier 2", "Driver 2", "2016-03-28", "TX - IN", "DRY", "1240", "", "", "This is a test note2");
$returned['resultCols']['id'] = 100;
$returned['resultCols']['cols'] = array("PO Number", "Load Date", "Customer(s)", "Customer PO", "Carrier", "Driver", "Delivery Date", "Lane", "Temp", "Weight", "Attention Date", "ND Date", "Notes");
echo json_encode($returned);
?>
I keep getting an error this.state.columns.map is not a function.
The same is true if I use this.props. So what am I doing wrong on this? I know how to make it work if I statically put in the data and insert that way on the since page but the call is not working.
You try to map a string at the beginning because of async $.get
replace this :
getInitialState: function() {
return {
results: '',
columns: ''
}
}
by this :
getInitialState: function() {
return {
results: [],
columns: []
}
}
EDIT TO MATCH PHP RETURN
var Table = React.createClass({
getInitialState: function() {
return {
results: [],
columns: []
}
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function(result) {
result = JSON.parse(result);
this.setState({
results: result['resultRows'],
columns: result['resultCols'].cols
});
}.bind(this));
},
componentWillUnmount: function(){
this.serverRequest.abort();
},
render: function() {
// Return the table.
return (
<table className="table table-condensed">
<thead>
<TableColumns data={this.state.columns} />
</thead>
<tbody>
{this.state.results.map(function(result) {
rows.push(<TableRow data={result.rows} key={result.id} />);
})}
</tbody>
</table>
);
}
});
// Set up columns
var TableColumns = React.createClass({
render: function() {
var colNodes = this.props.data.map(function(col, i){
return (
<th key={i}>{col}</th>
);
});
return (
<tr>
{colNodes}
</tr>
);
}
});
// Set up row
var TableRow = React.createClass({
render: function() {
var rowNodes = this.props.data.map(function(row, i){
return (
<td key={i}>{row}</td>
);
});
return (
<tr>
{rowNodes}
</tr>
);
}
});
var futureContainer = document.getElementById('loadboardContainer');
ReactDOM.render(<Table source="getTableValues.php" />, futureContainer);
I am getting a problem when trying to use DayPilot Calendar in angularjs.
https://code.daypilot.org/63034/angularjs-event-calendar-open-source
When I downloaded sources and use it it was not working and throwing error
angular.js:9563 TypeError: Cannot read property 'getTime' of undefined
at loadEvents (daypilot-all.min.js:11)
at update (daypilot-all.min.js:11)
at Object.fn (daypilot-all.min.js:11)
at h.$digest (angular.js:12031)
at h.$apply (angular.js:12279)
at g (angular.js:7991)
at C (angular.js:8196)
at XMLHttpRequest.y.onreadystatechange (angular.js:8137)
Source code of the downloaded code is
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DayPilot: AngularJS Event Calendar</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="js/daypilot/daypilot-all.min.js" type="text/javascript"></script>
<!-- helper libraries -->
<script src="js/jquery/jquery-1.9.1.min.js" type="text/javascript"></script>
<!-- daypilot libraries -->
<script src="js/daypilot/daypilot-all.min.js" type="text/javascript"></script>
<link type="text/css" rel="stylesheet" href="media/layout.css" />
</head>
<body>
<div id="header">
<div class="bg-help">
<div class="inBox">
<hr class="hidden" />
</div>
</div>
</div>
<div class="shadow"></div>
<div class="hideSkipLink">
</div>
<div class="main">
<div ng-app="main" ng-controller="DemoCtrl" >
<div style="float:left; width: 160px">
<daypilot-navigator id="navi" daypilot-config="navigatorConfig" ></daypilot-navigator>
</div>
<div style="margin-left: 160px">
<div class="space">
<button ng-click="showDay()">Day</button>
<button ng-click="showWeek()">Week</button>
</div>
<daypilot-calendar id="day" daypilot-config="dayConfig" daypilot-events="events" ></daypilot-calendar>
<daypilot-calendar id="week" daypilot-config="weekConfig" daypilot-events="events" ></daypilot-calendar>
</div>
</div>
<script>
var app = angular.module('main', ['daypilot']).controller('DemoCtrl', function($scope, $timeout, $http) {
$scope.events = [];
$scope.navigatorConfig = {
selectMode: "day",
showMonths: 3,
skipMonths: 3,
onTimeRangeSelected: function(args) {
$scope.weekConfig.startDate = args.day;
$scope.dayConfig.startDate = args.day;
loadEvents();
}
};
$scope.dayConfig = {
viewType: "Day",
onTimeRangeSelected: function(args) {
var params = {
start: args.start.toString(),
end: args.end.toString(),
text: "New event"
};
$http.post("backend_create.php", params).success(function(data) {
$scope.events.push({
start: args.start,
end: args.end,
text: "New event",
id: data.id
});
});
},
onEventMove: function(args) {
var params = {
id: args.e.id(),
newStart: args.newStart.toString(),
newEnd: args.newEnd.toString()
};
$http.post("backend_move.php", params);
},
onEventResize: function(args) {
var params = {
id: args.e.id(),
newStart: args.newStart.toString(),
newEnd: args.newEnd.toString()
};
$http.post("backend_move.php", params);
},
onEventClick: function(args) {
var modal = new DayPilot.Modal({
onClosed: function(args) {
if (args.result) { // args.result is empty when modal is closed without submitting
loadEvents();
}
}
});
modal.showUrl("edit.php?id=" + args.e.id());
}
};
$scope.weekConfig = {
visible: false,
viewType: "Week",
onTimeRangeSelected: function(args) {
var params = {
start: args.start.toString(),
end: args.end.toString(),
text: "New event"
};
$http.post("backend_create.php", params).success(function(data) {
$scope.events.push({
start: args.start,
end: args.end,
text: "New event",
id: data.id
});
});
},
onEventMove: function(args) {
var params = {
id: args.e.id(),
newStart: args.newStart.toString(),
newEnd: args.newEnd.toString()
};
$http.post("backend_move.php", params);
},
onEventResize: function(args) {
var params = {
id: args.e.id(),
newStart: args.newStart.toString(),
newEnd: args.newEnd.toString()
};
$http.post("backend_move.php", params);
},
onEventClick: function(args) {
var modal = new DayPilot.Modal({
onClosed: function(args) {
if (args.result) { // args.result is empty when modal is closed without submitting
loadEvents();
}
}
});
modal.showUrl("edit.php?id=" + args.e.id());
}
};
$scope.showDay = function() {
$scope.dayConfig.visible = true;
$scope.weekConfig.visible = false;
$scope.navigatorConfig.selectMode = "day";
};
$scope.showWeek = function() {
$scope.dayConfig.visible = false;
$scope.weekConfig.visible = true;
$scope.navigatorConfig.selectMode = "week";
};
loadEvents();
function loadEvents() {
// using $timeout to make sure all changes are applied before reading visibleStart() and visibleEnd()
$timeout(function() {
var params = {
start: $scope.week.visibleStart().toString(),
end: $scope.week.visibleEnd().toString()
}
$http.post("backend_events.php", params).success(function(data) {
$scope.events = data;
});
});
}
});
</script>
</div>
<div class="clear">
</div>
</body>
</html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
i am still confused why this problem is occurring again and again
You should check the response returned by "backend_events.php". DayPilot expects an array of events in JSON format. If there is any server-side error in the script the response will return an error message instead.
Most likely, there is a problem with permissions on the server side - the PHP script needs read/write permissions for daypilot.sqlite file which is in the application root.
So I am using Knockout Validation to validate my viewmodel and a custom knockout datepicker bindingHandler to attach a jQuery-UI datepicker to dynamically added items in my observableArray.
It seems my bindingHandler is destroying or breaking the validation rules on that field. Neither of the validation rules for the Start or End date seem to be getting enforced.
JSFiddle Link of my code
HTML code:
<form>
<a class="btn btn-default" data-bind="click: function () { $root.addMed(); }">Add New Medication</a>
<h6 data-bind="visible: patientMeds().length < 1">No medications entered.</h6>
<table class="table table-condensed" data-bind="visible: patientMeds().length > 0">
<thead>
<tr>
<th>Med</th>
<th>From</th>
<th>To</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: patientMeds">
<tr>
<td>
<input class="form-control" data-bind="value: MedicationID" />
</td>
<td>
<input class="form-control" data-bind="datepicker: StartDate, datepickerOptions: { changeMonth: true, changeYear: true, showButtonPanel: true }" />
</td>
<td>
<input class="form-control" data-bind="datepicker: DiscontinuedDate, datepickerOptions: { changeMonth: true, changeYear: true, showButtonPanel: true }" />
</td>
<td>
<button class="btn btn-default" data-bind="click: $parent.removeMed">Delete</button>
</td>
</tr>
</tbody>
</table>
</form>
Javascript / ViewModel code:
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
observable($(element).datepicker("getDate"));
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).datepicker("destroy");
});
}
};
function PatientMedication(p) {
var self = this;
p = p || {};
self.MedicationID = ko.observable(p.MedicationID || 1)
.extend({
required: {
params: true,
message: 'Please enter a medication'
},
number: true
});
self.StartDate = ko.observable(p.StartDate).extend({
required: {
params: true,
message: 'Please enter a date'
},
date: true
});
self.DiscontinuedDate = ko.observable(p.DiscontinuedDate || '').extend({
required: {
params: true,
message: 'Please enter a date'
},
date: true
});
}
function MedicationViewModel() {
var self = this;
self.patientMeds = ko.observableArray([]);
self.addMed = function () {
self.patientMeds.unshift(new PatientMedication());
};
self.removeMed = function (med) {
self.patientMeds.remove(med)
};
};
var medvm = new MedicationViewModel();
ko.applyBindings(medvm);
The validation plugin only hooks into the value, checked, textinput and selectedOptions bindings.
If you want to make your custom binding trigger the validations you need to call the validation.makeBindingHandlerValidatable method of the plugin and pass in the name of your custom binding:
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//...
}
};
ko.validation.makeBindingHandlerValidatable('datepicker');
Demo JSFiddle.
I have a jQuery modal dialog inside which I would like to pass data from a Knockout viewmodel. The dialog works fine as is - however, below code is broken.
Ideally, I would like to be able to click on the URI that triggers the modal dialog, and have the dialog load the data from the Knockout viewmodel. Any help would be greatly appreciated.
Markup:
List Names
<div id="listNames" data-bind="dataModel: { autoOpen: false, modal: true }">
<div>
<form action=''>
<p>You have added <span data-bind='text: name().length'> </span>
person(s)</p>
<table data-bind='visible: name().length > 0'>
<thead>
<tr><th>Select</th>
<th>Name</th>
<th>Age</th>
<th />
</tr>
</thead>
<tbody data-bind='foreach: metrics'>
<tr>
<td><input type="checkbox" /></td>
<td><span data-bind='text: name' > </span></td>
<td><span data-bind='text: age'> </span></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
ViewModel:
var dataModel = function (edata) {
var self = this;
self.edata = ko.observableArray(edata);
self.addname = function () {
self.edata.push({
name: "",
age: ""
});
};
self.removename = function (name) {
self.edata.remove(name);
};
self.save = function (form) {
alert("Could now transmit to server: "
+ ko.utils.stringifyJson(self.edata));
// To actually transmit to server as a regular form post, write this:
// ko.utils.postJson($("form")[0], self.edata);
};
};
var viewModel = new dataModel([
{ name: "Jack", age: "41" },
{ name: "Jill", age: "33" }
]);
ko.applyBindings(new viewModel);
jQuery Dialog:
$("#listNames, ").dialog({
autoOpen: false,
width: 300,
modal: true,
buttons: {
"OK": function () {
$(this).dialog("destroy");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$("#openList")
.click(function () {
$("#listNames").dialog("open");
});
There are a few errors in the code you posted.
I have a working version here : http://jsfiddle.net/uFgz8/1/
Here is the HTML :
Open dialog //you had 2 elements with the same ID, I removed the ID on the link and bound it to a method in the view model
<div id="listNames"> <div>
<form action=''>
<p>You have added <span data-bind='text: name.length'> </span> person(s)</p> // name item is not observable, so you cannot use name().length
<table data-bind='visible: name.length > 0'> // same remark for name
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>Age</th>
<th />
</tr>
</thead>
<tbody data-bind='foreach: edata'>
<tr>
<td>
<input type="checkbox" />
</td>
<td><span data-bind='text: name'> </span>
</td>
<td><span data-bind='text: age'> </span>
</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
The JS:
$("#listNames").dialog({
autoOpen: false,
width: 300,
modal: true,
buttons: {
"OK": function () {
// do something
$(this).dialog("close"); // I replaced destroy by close, so it can be opened after ok has been clicked
},
Cancel: function () {
$(this).dialog("close");
}
}
});
var dataModel = function (edata) {
var self = this;
self.edata = ko.observableArray(edata);
self.addname = function () {
self.edata.push({
name: "",
age: ""
});
};
self.openDialog = function () {
$("#listNames").dialog("open");
};
self.removename = function (name) {
self.edata.remove(name);
};
self.save = function (form) {
alert("Could now transmit to server: " + ko.utils.stringifyJson(self.edata));
// To actually transmit to server as a regular form post, write this: ko.utils.postJson($("form")[0], self.edata);
};
};
var viewModel = new dataModel([{
name: "Jack",
age: "41"
}, {
name: "Jill",
age: "33"
}]);
ko.applyBindings(viewModel); // you have created a variable viewModel with data, but you bound ko with a new object of type viewModel, you must either call ko with viewModel you created, or inline the creation of a new "dataModel"
edit : I added some comments to my changes
edit 2 : I updated the link to the jsfiddle to get to the correct version ;)