knockout form validation message - javascript

I'd like to use Knockout.js to highlight errors on a form.
Currently i see all errors when i get the form,
I want to get them only if the user press on Save button.
So I'm try to set a flag that will be true only if the user press on it, and then to use it in all form but i don't have success with that.
I will apreciate some help with that. (or any other way to do it)
so i will need someting like that on my html:
<div class='liveExample' data-bind="css: {hideErrors: !hasBeenSubmittedOnce()">
and somewhere in my js file:
this.hasBeenSubmittedOnce = ko.observable(false);
this.save = function(){
this.hasBeenSubmittedOnce(true);
}
that my files
HTML
<div class='liveExample' data-bind="css: {hideErrors: !hasBeenSubmittedOnce()">
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-sm-3 control-label">Store:</label>
<div class="col-sm-3" data-bind="css: { error: storeName.hasError() }">
<input data-bind='value: storeName, valueUpdate: "afterkeydown"' />
<span data-bind='text: storeName.validationMessage'> </span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Company ID:</label>
<div class="col-sm-3" data-bind="css: { error: companyId.hasError }">
<input data-bind='value: companyId, valueUpdate: "afterkeydown"' />
<span data-bind='text: companyId.validationMessage'> </span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Address</label>
<div class="col-sm-3" data-bind="css: { error: address.hasError }">
<input data-bind='value: address, valueUpdate: "afterkeydown"' />
<span data-bind='text: address.validationMessage'> </span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Phone:</label>
<div class="col-sm-3" data-bind="css: { error: phone.hasError }">
<input data-bind='value: phone, valueUpdate: "afterkeydown"' />
<span data-bind='text: phone.validationMessage'> </span>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-4">
<button class="btn btn-primary" data-bind="click: save">Add store</button>
</div>
</div>
</form>
Store:
Company ID:
Address
Phone:
Add store
</form>
js
define(['knockout'], function (ko){
ko.extenders.required = function(target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError(newValue ? false : true);
target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
}
validate(target());
target.subscribe(validate);
return target;
};
function AppViewModel(storeName, companyId, address, phone) {
this.storeName = ko.observable(storeName).extend({ required:"" });
this.companyId = ko.observable(companyId).extend({ required: "" });
this.address = ko.observable(address).extend({ required: "" });
this.phone = ko.observable(phone).extend({ required: ""});
this.hasError = ko.computed(function(){
return this.storeName.hasError() || this.companyId.hasError();
}, this);
this.hasBeenSubmittedOnce = ko.observable(false);
this.save = function(){
this.hasBeenSubmittedOnce(true);
}
}
return AppViewModel;
});
CSS file
.form-group span {
display: inherit;
}
.hideErrors .error span {
display: none;
}

I did some work around for this and not sure it is better way or not.
var showError=ko.observableArray([]);//it will store show Error Message
ko.extenders.required = function(target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError($.trim(newValue) ? false : true);
target.validationMessage($.trim(newValue) ? "" : overrideMessage || "This field is required");
}
showError.push(function(){validate(target());});
target.subscribe(validate);
return target;
};
function AppViewModel(storeName, companyId, address, phone) {
this.storeName = ko.observable(storeName).extend({ required:"" });
this.companyId = ko.observable(companyId).extend({ required: "xcxcx" });
this.address = ko.observable(address).extend({ required: "" });
this.phone = ko.observable(phone).extend({ required: ""});
this.hasError = ko.computed(function(){
return self.storeName.hasError() || self.companyId.hasError();
}, this);
this.hasBeenSubmittedOnce = ko.observable(false);
this.save = function(){
ko.utils.arrayForEach(showError(),function(func){
func();
});
}
}
ko.applyBindings(new AppViewModel());
Fiddle Demo

You can use the visible knockout binding:
<div data-bind="visible: hasBeenSubmittedOnce">
As for the error class, you can use the define the default knockout validation class: 'validationElement' and call
ko.validation.init({ decorateElement: true});
Here you can find more:
https://github.com/Knockout-Contrib/Knockout-Validation/wiki/Configuration
(please note that decorateElement has been renamed 2013-11-21 to 'decorateInputElement')

Related

AngularJs- Redirect to another view after submitting data to the server

I'm developing a small AngularJs and ASP.net MVC based web application with MongoDb database. And one of it's task is to register yourself if not an already a member. And after successfully submitting data from client side to the server, the user should be redirected to another page.So Data get saved in the database after the submission but It's does not seem to trigger the success function of Angular part where i try to redirect to the other page.
I have attached the image showing non-triggering part of the code highlighting in yellow.
How can i resolve this ? Any help would be appreciated.
[HttpPost]
public JsonResult RegisterUser(User user)
{
mongoClient = new MongoClient();
var db = mongoClient.GetDatabase(Database);
userList = db.GetCollection<User>("user");
var result = userList.AsQueryable().Where(a => a.UserName.Equals(user.UserName)).SingleOrDefault();
user.IsActive = true;
user.UserType = "Visitor";
string message = "";
if (result == null)
{
var seralizedUser = JsonConvert.SerializeObject(userList);
userList.InsertOne(user);
//var seralizedUser = new JavaScriptSerializer().Serialize(userList);
message = "Success";
//return Json(seralizedUser, JsonRequestBehavior.AllowGet);
return Json(new
{
redirectUrl = Url.Action("VisitorChatPanel", "Visitor", ""),
isRedirect = true
});
// return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
else
{
message = "Failed";
//var seralizedUser = new JavaScriptSerializer().Serialize(userList);
var seralizedUser = JsonConvert.SerializeObject(userList);
// return Json(seralizedUser, JsonRequestBehavior.AllowGet);
return Json(new
{
redirectUrl = Url.Action("VisitorChatPanel", "Visitor", ""),
isRedirect = false
});
}
}
angular.module('MyApp', [])
.controller('VisitorRegistrationController', function ($scope, RegistrationService) {
$scope.SubmitText = "Save";
$scope.IsFormValid = false;
$scope.Submitted = false;
$scope.Message = '';
$scope.User = {
UserName: '',
Password: '',
Email: '',
FirstName: '',
LastName: '',
IsActive: false,
UserType: 'Visitor'
};
//validates form on client side
$scope.$watch('f1.$valid', function (newValue) {
$scope.isFormValid = newValue;
});
//Save Data
$scope.SaveData = function (data) {
if ($scope.SubmitText == 'Save') {
$scope.Submitted = true;
$scope.Message = '';
if ($scope.isFormValid) {
// $scope.SubmitText = 'Please Wait...';
$scope.User = data;
alert('data : ' + $scope.User.FirstName);
RegistrationService.SaveFormData($scope.User).then(function (d) {
alert(d);
if (d == 'Success') {
//have to clear form here
ClearForm();
}
$scope.SubmitText = "Save";
});
}
else {
$scope.Message = '';
}
}
}
//Clear Form
function ClearForm() {
$scope.User = {};
$scope.f1.$setPristine(); //here f1 is form name
$scope.Submitted = false;
}
}).factory('RegistrationService', function ($http, $q) {
var fac = {};
fac.SaveFormData = function (data) {
//alert('$http : ' + $http);
var defer = $q.defer();
alert('q : ' + $q);
$http({
url: '/Visitor/RegisterUser',
method: 'POST',
data: JSON.stringify(data),
headers: {'content-type' : 'application/json'}
}).success(function (d) {
// Success callback
alert('Successfully registered !');
if (d.isRedirect) {
window.location.href = d.redirectUrl;
}
defer.resolve(d);
}).error(function (e) {
//Failed Callback
alert('Error!');
// defer.reject(e);
});
return defer.promise;
//return 'Successfull';
}
return fac;
});
;
#{
ViewBag.Title = "VisitorRegistrationForm";
}
<style>
body {
margin-top: 50px;
}
input {
max-width: 300px;
}
.error {
color: red;
}
</style>
<h2>Visitor Registration Form</h2>
<div class="panel panel-info" style="margin-left:30px;margin-right:500px;">
<div ng-controller="VisitorRegistrationController" class="panel-body">
<form novalidate name="f1" ng-submit="SaveData(User)" class="form-horizontal">
<div class="form-group">
<label class="text text-info col-md-offset-2">First Name : </label>
<input type="text" ng-model="User.FirstName" class="form-control col-md-offset-2" name="uFirstName" ng-class="Submitted?'ng-dirty':''" required autofocus />
<span class="error col-md-offset-2" ng-show="(f1.uFirstName.$dirty || Submitted) && f1.uFirstName.$error.required">FirstName required!</span>
</div>
<div class="form-group">
<label class="text text-info col-md-offset-2">Last Name : </label>
<input type="text" ng-model="User.LastName" class="form-control col-md-offset-2" name="uLastName" ng-class="Submitted?'ng-dirty':''" required autofocus />
<span class="error col-md-offset-2" ng-show="(f1.uLastName.$dirty || Submitted) && f1.uLastName.$error.required">LastName required!</span>
</div>
<div class="form-group">
<label class="text text-info col-md-offset-2">Email : </label>
<input type="email" ng-model="User.Email" class="form-control col-md-offset-2" name="uEmail" ng-class="Submitted?'ng-dirty':''" />
<span class="error col-md-offset-2" ng-show="(f1.uEmail.$dirty || Submitted) && f1.uEmail.$error.required">Email required</span>
<span class="error col-md-offset-2" ng-show="(f1.uEmail.$dirty || Submitted) && f1.uEmail.$error.email">Email not valid!</span>
</div>
<div class="form-group">
<label class="text text-info col-md-offset-2">UserName : </label>
<input type="text" ng-model="User.UserName" class="form-control col-md-offset-2" name="uUserName" ng-class="Submitted?'ng-dirty':''" required />
<span class="error col-md-offset-2" ng-show="(f1.uUserName.$dirty || Submitted) && f1.uUserName.$error.required">UserName required!</span>
</div>
<div class="form-group">
<label class="text text-info col-md-offset-2">Password : </label>
<input type="password" ng-model="User.Password" class="form-control col-md-offset-2" name="uPassword" ng-class="Submitted?'ng-dirty':''" required />
<span class="error col-md-offset-2" ng-show="(f1.uPassword.$dirty || Submitted) && f1.uPassword.$error.required">Password required!</span>
</div>
<div class="form-group">
<label></label>
<input type="submit" class="btn btn-success col-md-offset-2" value="{{SubmitText}}" />
</div>
</form>
</div>
</div>

bootstrap form validation only one field required

I have a form that has userID and screen name input fields.
When validating I need to make sure that at least one of them is entered (if both were entered I only take one). The html:
this.addFormValidators = function () {
$('#editCreatePipeForm').formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
ConsumerKey: {
validators: {
notEmpty: {
message: 'The Consumer Key is required'
}
}
},
ConsumerKeySecret: {
validators: {
notEmpty: {
message: 'The Consumer Key Secret is required'
}
}
},
CollectionIntervalSec: {
validators: {
notEmpty: {
message: 'The collection interval is required'
},
between: {
message: 'The collection interval must be a number greater than 10',
min: 10,
max: 1000000000
}
}
},
//KeepHistoricalDataTimeSec: {
// validators: {
// notEmpty: {
// message: 'The retain data value is required'
// },
// between: {
// message: 'The retain data value must be a number greater than 1000',
// min: 1000,
// max: 1000000000
// }
// }
//},
Description: {
validators: {
stringLength: {
max: 500,
message: 'The description must be less than 500 characters long'
}
}
}
}
}, null);
};
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="ScreenName" class="col-md-4 YcdFormLabel" title="screen name of user to retrieve">Screen name</label>
<div class="col-md-8">
<input type="text" placeholder="Screen Name" class="form-control user" autocomplete="off"
name="screenName"
id="screenName" data-bind="value: screenName, valueUpdate: 'keyup'"/>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"/>
<div class="col-md-6">
<div class="form-group">
#*<div class="col-md-8">*#
<label for="or" class="col-md-10">or</label>
#*</div>*#
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="userID" class="col-md-4 YcdFormLabel" title="user_ID of user to retrieve">User ID</label>
<div class="col-md-8">
<input type="text" placeholder="User ID" class="form-control user" autocomplete="off"
name="userID"
id="userID" data-bind="value: userID, valueUpdate: 'keyup'"/>
</div>
</div>
</div>
</div>
I added another function which I called it before submitting instead of using Bootstrap and jQuery form validation.
private hasTimelineAndUsername = (): boolean => {
if (this.viewModel.searchSelection() == "timeline"
&& ((this.viewModel.userID() == "" ||
this.viewModel.userID() == null) &&
(this.viewModel.screenName() == "" ||
this.viewModel.screenName() == null))) {
return false
}
return true;
}
The submitting function:
public getCollectionParameters() {
var fv = $('#editCreatePipeForm').data('formValidation')
fv.validate();
var isValid = fv.isValid();
if (!isValid) {
toastr.error("Please fix all problems before saving");
return null;
}
if (!this.hasTimelineAndUsername()) {
toastr.clear();
toastr.error("Please type username/userID");
return null;
}
if (!this.validateData()) {
return null;
}
return JSON.stringify(ko.mapping.toJS(this.viewModel));
}
I hope my code will help you.
JSFiddle: https://jsfiddle.net/aice09/3wjdvf30/
CodePen: https://codepen.io/aice09/pen/XgQyem
GitHub: https://github.com/Ailyn09/project102/blob/master/chooseintwoinput.html
function verify() {
var screenName = document.getElementById("screenName").value;
var userID = document.getElementById("userID").value;
if (userID === '' && screenName === '') {
alert('Add value to any field');
}
if (userID !== '' && screenName === '') {
alert('Your screen name are currently empty. The value you will be taken is your screen name');
document.getElementById("takedvalue").value = userID;
}
if (userID === '' && screenName !== '') {
alert('Your user id are currently empty. The value you will be taken is your user identification');
document.getElementById("takedvalue").value = screenName;
}
if (userID !== '' && screenName !== '') {
document.getElementById("mainbtn").style.display = "none";
document.getElementById("backbtn").style.display = "initial";
document.getElementById("choosescreenName").style.display = "initial";
document.getElementById("chooseuserID").style.display = "initial";
}
}
//Reset Form
$('.backbtn').click(function () {
document.getElementById("mainbtn").style.display = "initial";
document.getElementById("backbtn").style.display = "none";
document.getElementById("choosescreenName").style.display = "none";
document.getElementById("chooseuserID").style.display = "none";
});
//Choose First Input
$('.choosescreenName').click(function () {
var screenName = document.getElementById("screenName").value;
document.getElementById("takedvalue").value = screenName;
});
//Choose Second Input
$('.chooseuserID').click(function () {
var userID = document.getElementById("userID").value;
document.getElementById("takedvalue").value = userID;
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<div class="container">
<form action="POST">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="screenName">Screen name</label>
<input type="text" placeholder="Screen Name" class="form-control " autocomplete="off" name="screenName" id="screenName" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="userID">User ID</label>
<input type="text" placeholder="User ID" class="form-control user" autocomplete="off" name="userID" id="userID" />
</div>
</div>
<div class="col-md-12">
<button type="button" class="btn btn-primary" id="mainbtn" onclick="verify();">SUBMIT</button>
<button type="reset" class="btn btn-primary backbtn" id="backbtn" style="display:none;">BACK</button>
<button type="button" class="btn btn-primary choosescreenName" id="choosescreenName" style="display:none;">CHOOSE SCREEN NAME</button>
<button type="button" class="btn btn-primary chooseuserID" id="chooseuserID" style="display:none;">CHOOSE USER ID</button>
</div>
<div class="col-md-12">
<hr>
<div class="form-group">
<label for="userID">Value</label>
<input type="text" placeholder="Taken Value" class="form-control" id="takedvalue" readonly />
</div>
</div>
</div>
</form>
</div>

knockout.ja validation error in nested viewmodels

I have a problem in using knockout.js validation plug in. when I try to define 'errors' in newPerson viewmodel the compiler says that newPerson is undefined. Totally, is it correct to use knockout-validation with object type of viewmodels instead of function type?
var clientModel = {
newPerson: {
EmailAddress: ko.observable().extend({
required: {
params: true,
message: "This field is required"
},
emailFormatCheck: {
params: true,
message: ""
}
}),
errors: ko.validation.group(newPerson, {
deep: true
})
}
}
ko.extenders.emailFormatCheck = function(target, overrideMessage) {
target.hasError = ko.observable();
target.validationMessage = ko.observable();
function validate(newValue) {
var matches = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i.exec(newValue);
if (matches == null) {
target.hasError(true);
target.validationMessage("The email format is wrong!!!");
} else {
target.hasError(false);
}
}
validate(target());
target.subscribe(validate);
return target;
};
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true
});
ko.applyBindings();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<div class="panel panel-primary">
<div class="panel-heading"></div>
<div class="panel-body">
<form role="form" data-bind="with: clientMode.newPerson">
<div class="form-group">
<p data-bind="css: { error: EmailAddress.hasError }">
<label>Email</label>
<br />
<input class="form-control" data-bind="value: EmailAddress, valueUpdate: 'afterkeydown'" /> <span data-bind="visible: EmailAddress.hasError, text: EmailAddress.validationMessage"> </span>
</p>
</div>
<br />
</form>
</div>
<div class="panel-footer">
<button type="submit" class="btn btn-default" data-bind=" enable:!clientModel.errors().length">Creat</button>
</div>
</div>
Thank you in advance

Use CKeditor instance in Vue.js

I am trying to implement CKeditor in my Laravel-backoffice which build its views with Vue.js
In this form I want to replace the "textarea" with name="ckeditor1" with a texteditor
<form method="POST" v-on="submit: onSubmitForm">
<div class="col-md-4">
<h1>Pagina: #{{ page.name }}</h1>
<h2>Pagina algemeen</h2>
<div class="form-group">
<label for="name">
Name
<span class="error" v-if="! page.name">*</span>
</label>
<input type="text" name="name" id="name" class="form-control" v-model="page.name">
</div>
<ul class="nav nav-tabs">
<li class="" v-repeat="page.translations" v-class="active: language == defaultLanguage"><a
data-toggle="tab" href="##{{ language }}">#{{ language }}</a></li>
</ul>
<div class="tab-content">
<div v-repeat="page.translations" id="#{{ language }}" class="tab-pane fade in "
v-class="active: language == defaultLanguage">
<h2>Pagina inhoud</h2>
<div class="form-group">
<label for="name">
Titel
</label>
<input type="text" name="title_#{{ language }}" id="title_#{{ language }}"
class="form-control" v-model="title">
</div>
<div class="form-group">
<label for="content">
Inhoud
</label>
<textarea name="ckeditor1" id="content_#{{ language }}"
class="form-control editor" v-model="content"></textarea>
</div>
<h2>Seo</h2>
<div class="form-group">
<label for="meta_keywords">
Meta keywords
</label>
<input type="text" name="meta_keywords_#{{ language }}"
id="meta_keywords_#{{ language }}" class="form-control"
v-model="meta_keywords">
</div>
<div class="form-group">
<label for="meta_decription">
Meta description
</label>
<textarea name="meta_description_#{{ language }}"
id="meta_description_#{{ language }}" class="form-control"
v-model="meta_description"></textarea>
</div>
<input type="hidden" name="page_id_#{{ language }}" id="page_id_#{{ language }}"
class="form-control" v-model="page_id" value="#{{ pageId }}">
</div>
</div>
<div class="form-group" v-if="! submitted">
<button type="submit" class="btn btn-default">
Opslaan
</button>
</div>
</div>
</form>
The #{{ }} fields are loaded and filled with json call and vue.js but there is no problem cause all fields are filled perfectly as needed. The problem is just the initializing of my editor.
This is where I get my data:
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
var pages = new Vue({
el: '#page',
data: {
pageId: document.querySelector('#page-id').getAttribute('value'),
pageTitle: 'Pagina',
page: [],
submitted: false,
defaultLanguage: 'nl',
errors: false
},
ready: function() {
this.fetch();
},
methods: {
fetch: function() {
this.$http.get('/api/pages/' + this.pageId, function(response) {
this.page = response;
});
},
onSubmitForm: function(e) {
e.preventDefault();
this.submitted = true;
this.errors = false;
if(this.pageId == 0) {
this.$http.post('/api/pages/', this.page, function (response) {
if (response.errors.length) {
this.errors = response.errors;
this.submitted = false;
return;
}//endif
this.submitted = false;
window.location.href = '/admin/pages';
});
}
else
{
this.$http.put('/api/pages/' + this.pageId, this.page, function (response) {
if (response.errors.length) {
this.errors = response.errors;
this.submitted = false;
return;
}//endif
this.submitted = false;
window.location.href = '/admin/pages';
});
}
}
}
});
UPDATE -> SOLVED
By adding Vue.nextTick I can initialize an editor. I added a class 'editor' to every textarea I want it to be an editor and then find all id's from the textareas with class="editor".
fetch: function() {
this.$http.get('/api/pages/' + this.pageId, function(response) {
this.page = response;
Vue.nextTick(function () {
$('textarea.editor').each(function(){
CKEDITOR.replace(this.id);
});
});
});
},
By adding Vue.nextTick I can initialize an editor. I added a class 'editor' to every textarea I want it to be an editor and then find all id's from the textareas with class="editor".
fetch: function() {
this.$http.get('/api/pages/' + this.pageId, function(response) {
this.page = response;
Vue.nextTick(function () {
$('textarea.editor').each(function(){
CKEDITOR.replace(this.id);
});
});
});
}
I am also using CKeditor with laravel-vue. You just need to set and get data with CKeditor for basic thing.
This is my main.html file in which i need CKeditor.
<div class="row">
<div class="col-md-2">
<label for="body" >Mail Body :</label>
</div>
<div class="col-md-10" >
<textarea class="ckeditor" id="body" rows="5" cols="70" name="body" v-model="template.body" ></textarea>
</div>
</div>
After that i initialize my CKeditor value in app.js file
var vm = this;
axios.post('/fetchEmailTemplate', {
'template_id' : template_id
}).then(function (response) {
vm.template = response.data.emailTemplate;
CKEDITOR.instances['body'].setData(vm.template.body);
}).catch(function (error) {
console.log(error);
setNotification(error, "danger");
});
If I'm not mistaken ckeditor replaces the original textarea by a custom template. So what you see within ckeditor will not be put into your messageArea textarea automatically. That's why you don't see any changes to your model. So, for making changes you need to replace updated text before submit in app.js file like below.
this.template.body = CKEDITOR.instances['body'].getData();

$parent.myFunction not returning row as parameter in KnockoutJs

I'm using knockoutjs for the first time in an attempt to have a list of tasks and then to be able to click on one to show it in a popup form. The issue I'm having is with data-bind="click: $parent.edit", which calls ToDoListViewModel/edit.
When I first started writing the list code, it would pass in the current row's todo object as the first parameter into the edit function. After adding the second view model for my add/edit popup form, it no longer behaves this way. Calling $parent.edit still calls the edit function, however now it passes in an empty object { }.
It seems like I'm running into some sort of conflicting bindings issue, any ideas?
Here is the to do list html:
<table class="table table-striped table-hover" data-bind="visible: isVisible">
<thead>
<tr>
<th>To-Do</th>
<th>Estimate</th>
<th>Deadline</th>
#if (Model == null) { <th>Property</th> }
<th>Tenant</th>
<th style="display: none;">Assigned To</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: todos">
<tr data-bind="visible: isVisible()">
<td><a class="pointer" title="Edit To-Do" data-bind="click: $parent.edit, text: Task"></a></td>
<td data-bind="text: FormattedAmount"></td>
<td data-bind="text: FormattedDueDate"></td>
<td data-bind="visible: $parent.showPropertyColumn, text: PropertyName"></td>
<td data-bind="text: TenantName"></td>
<td>
<div class="btn-group pull-right">
<a class="btn btn-primary pointer default-click-action" data-bind="click: $parent.markComplete">Mark Complete</a>
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a class="pointer" data-bind="click: $parent.edit">Edit To-Do</a></li>
<li><a class="pointer" data-bind="click: $parent.remove">Delete To-Do</a></li>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
And here is the popup html:
#model Housters.Schemas.Models.Property.Listing
<div id="popup" class="modal fade" style="display: none;" data-bind="with: form">
#using (Html.BeginForm("SaveTodo", "Properties", FormMethod.Post, new { Id = "form", #class = "form-horizontal" }))
{
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>To-Do Information</h3>
</div>
<div class="modal-body">
<input id="id" name="id" type="hidden" data-bind="value: todo().Id" />
<input id="originalListingId" type="hidden" value="#(Model != null ? Model.IdString : "")" />
<div class="control-group #(Model != null ? " hide" : "")">
<label class="control-label" for="listingId">Property</label>
<div class="controls">
#Html.DropDownList("listingId", ViewBag.Listings as SelectList, "None",
new Dictionary<string, Object> { { "data-bind", "value: todo().ListingId" } })
</div>
</div>
<div class="control-group">
<label class="control-label" for="tenantId">Tenant</label>
<div class="controls">
<select id="tenantId" name="tenantId" class="span11" data-bind="value: todo().TenantId">
<option value="">None</option>
</select>
<p class="help-block">Is this task related to a certain tenant?</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="amount">Estimate to Complete</label>
<div class="controls">
<div class="input-prepend"><span class="add-on">$</span><input type="text" id="amount" name="todo.Amount" maxlength="10"
class="span11 number" data-bind="value: todo().Amount" /></div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="dueDate">Due Date</label>
<div class="controls">
<input type="text" id="dueDate" name="todo.DueDate" maxlength="10"
class="span11 date" data-bind="value: todo().DueDate" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="task">Task<span class="required-asterisk">*</span></label>
<div class="controls">
<textarea id="task" name="todo.Task" rows="4" class="span11 required" data-bind="value: todo().Task"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn pointer" data-dismiss="modal">Close</a>
<a id="mark-complete-popup" class="btn btn-primary" data-dismiss="modal" data-bind="visible: (todo().Id && !todo().IsComplete), click: markComplete">Mark Complete</a>
<button type="button" class="btn btn-primary" data-bind="click: save">Save</button>
</div>
}
</div>
And lastly, here is the javascript defining the view models:
function ToDoList () {
if(!(this instanceof arguments.callee))
return new arguments.callee();
var parent = this;
this.showCompleted = ko.observable(false);
this.tenantFilter = new PropertyTenantFilter();
this.viewModel = {
list: new ToDoListViewModel(),
form: new ToDoFormViewModel()
};
this.init = function () {
//get all tenants.
utils.block($("#grid-content"), "Loading");
this.tenantFilter.init(function () {
//initialize view model.
ko.applyBindings(this.viewModel);
//setup controls & events.
$("#dueDate").datepicker();
$("#listingId").change(this.tenantFilter.getByListing.bind(this.tenantFilter)).change();
} .bind(this));
};
function ToDoListViewModel() {
//init.
var self = this;
self.todos = ko.observableArray([]);
//computed.
self.showPropertyColumn = ko.computed(function () {
return $("#originalListingId").val().length == 0;
});
self.isVisible = ko.computed(function () {
return _.find(self.todos(), function (todo) { return todo.isVisible(); }) != null;
});
//operations.
self.add = function () {
//set form field values.
parent.viewModel.form.fill(new schemas.ToDo({}, parent));
//show popup.
$("#popup").modal("show");
};
self.edit = function (todo) {
console.debug("edit: " + JSON.stringify(todo));
//set form field values.
parent.viewModel.form.fill(todo);
//update tenants dropdown for selected listing.
parent.tenantFilter.getByListing();
//show popup.
$("#popup").modal("show");
};
self.markComplete = function (todo) {
parent.markComplete(todo);
};
self.remove = function (todo) {
var result = confirm("Are you sure that you want to delete this To-Do?");
if (result) {
//save changes.
utils.ajax(basePath + "properties/deletetodo",
{ id: todo.Id },
function (success) {
//refresh results.
self.todos.remove(todo);
//show result.
utils.showSuccess('The To-Do has been deleted successfully');
}
);
}
};
self.toggleShowCompleted = function () {
parent.showCompleted(!parent.showCompleted());
$("#showCompletedTodos").text(parent.showCompleted() ? "Show Active" : "Show Completed");
};
self.update = function (todo) {
var existingToDo = _.find(self.todos(), function (item) { return item.Id() == todo.Id(); });
existingToDo = todo;
};
//load todos from server.
utils.ajax(basePath + "properties/gettodos",
{ id: $("#originalListingId").val(), showCompleted: parent.showCompleted() },
function (results) {
var mappedTodos = $.map(results, function (item) { return new schemas.ToDo(item, parent); });
self.todos(mappedTodos);
$("#grid-content").unblock();
}
);
}
function ToDoFormViewModel() {
//init.
var self = this;
self.todo = ko.observable({});
utils.setupPopupForm(self.saved);
//operations.
self.fill = function (todo, isEdit) {
//set form field values.
self.todo = todo;
if (todo.Id()) {
//update tenants dropdown for selected listing.
parent.tenantFilter.getByListing();
}
//show popup.
$("#popup").modal("show");
};
self.save = function (todo) {
self.todo = todo;
$("#form").submit();
};
self.saved = function (result) {
var todo = new schemas.ToDo(result.todo, parent);
if (result.isInsert)
parent.viewModel.list.todos().push(todo);
else
parent.viewModel.list.update(todo);
utils.showSuccess("Your To-Do has been saved successfully.");
};
self.markComplete = function (todo) {
parent.markComplete(todo);
};
}
this.markComplete = function (todo) {
var result = confirm("Are you sure that you want to mark this To-Do complete?");
if (result) {
//save changes.
utils.ajax(basePath + "properties/marktodocomplete", {
id: todo.Id()
},
function () {
todo.IsComplete(true);
//show success.
utils.showSuccess('Your To-Do has been marked completed');
} .bind(this)
);
}
}
this.init();
}
One possible solution is to replace:
data-bind="click: $parent.edit"
with
data-bind="click:$root.viewModel.list.edit"

Categories

Resources