We have a multiple page form like below , each page on the form is associated with different model classes. I am trying use the value the users selected in Page 1 and based upon that value selected in Pg1 I need to show/hide the field in Page2.
Page2 has a button which allows the users add courses, when they click on the button few fields shows up in the page in foreach loop and one of the field should show/hide based on the selection made on the previous page. But the above logic throws error like Uncaught ReferenceError: Unable to process binding "visible:" below is the viewmodel
How can I have the binding work properly here and get rid of the error
It's case sensitive. Also, the foreach loop changes the binding context, so you need to do this:
<div class="form-group required" data-bind="visible: $parent.Solution() == 'Other'">
Edit- that is, if you're indeed trying to reference the Solution property from the parent viewmodel. It's not clear from your example wheter a CoursesList item also has such a property.
Just expanding on #Brother Woodrow's answer with an very basic runnable example might help with things.
function ViewModel() {
var self = this;
self.pages = [1, 2]
self.currentPage = ko.observable(1)
self.solutions = ko.observableArray(['Solution 1', 'Solutions 2', 'Other']);
self.solution = ko.observable().extend({
required: {
params: true,
message: "Required"
}
});
self.next = function() {
self.currentPage(self.currentPage() + 1);
};
self.back = function() {
self.currentPage(self.currentPage() - 1);
};
self.CourseDetails = ko.observableArray();
self.addCourse = function() {
self.CourseDetails.push(new coursesList());
}
self.pageVisible = function(page) {
return self.currentPage() == page;
}
}
function coursesList() {
var self = this;
self.otherSolution = ko.observable().extend({
required: {
params: true,
message: "Required"
}
});
}
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="Page_1" data-bind="visible: pageVisible(1)">
<h2>Page 1</h2>
<div class="form-group required">
<label for="Solution" class="control-label">Solution</label>
<select id="Solution" name="Solution" class="form-control" data-bind="options: solutions, value: solution, optionsCaption: 'Select'"></select>
</div>
<button type="submit" id="NtPg" class="SubmitButton" data-bind="click: next">Next</button>
</div>
<div id="Page_2" data-bind="visible: pageVisible(2)">
<h2>Page 2</h2>
<button type="submit" id="AddCourseInfo" class="SubmitButton" data-bind="click: addCourse">Add Course Info</button>
<div data-bind="foreach:CourseDetails">
<div class="form-group required" data-bind="visible: $parent.solution() == 'Other'">
<label for="OtherSolution" class="control-label">Explain Other Solution : </label>
<input type="text" maxlength="1000" id="OtherSolution" name="OtherSolution" class="form-control" data-bind="value : otherSolution" required/>
</div>
</div>
<button type="submit" id="NtPg" class="SubmitButton" data-bind="click: back">Back</button>
</div>
<pre data-bind="text: ko.toJSON($root)"></pre>
Related
I have save method on modal window once user execute save method i want to clear the form fields, I have implemented $setPristine after save but its not clearing the form. How to achieve that task using angularJS ?
So far tried code....
main.html
<div>
<form name="addRiskForm" novalidate ng-controller="TopRiskCtrl" class="border-box-sizing">
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="topRiskName" class="required col-md-4">Top Risk Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="topRiskName" ng-model="topRiskDTO.topRiskName"
name="topRiskName" required>
<p class="text-danger" ng-show="addRiskForm.topRiskName.$touched && addRiskForm.topRiskName.$error.required">Top risk Name is required field</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="issuePltfLookUpCode" class="col-md-4">Corresponing Issue Platform:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="issuePltfLookUpCode"
k-option-label="'Select'"
ng-model="topRiskDTO.issuePltfLookUpCode"
k-data-source="issuePltDataSource"
id="issuePltfLookUpCode">
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="issueNo" class="col-md-4">Issue/Risk Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="issueNo" ng-model="topRiskDTO.issueNo"
name="issueNo">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addRiskForm.$invalid" ng-click="submit()">Save</button>
<button class="btn btn-primary pull-right" ng-click="handleCancel">Cancel</button>
</div>
</form>
</div>
main.js
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
$scope.$emit('refreshTopRiskGrid');
$scope.addRiskForm.$setPristine();
});
};
});
Hey interesting question and I have messed around with it and I have come up with something like this (I have abstracted the problem and simplified it, it is up to you to implent it to your likings). Likely not super elegant but it does the job: Fiddle
<div ng-app="app">
<div ng-controller="main">
<form id="form">
<input type="text" />
<input type="text" />
</form>
<button ng-click="clear()">clear</button>
</div>
</div>
JS
angular.module("app", [])
.controller("main", function ($scope) {
$scope.clear = function () {
var inputs = angular.element(document.querySelector('#form')).children();
angular.forEach(inputs, function (value) {
value.value="";
});
};
})
Hope it helps.
Edit
If you give all your inputs that must be cleared a shared class you can select them with the querySelector and erase the fields.
Refer to this page: http://blog.hugeaim.com/2013/04/07/clearing-a-form-with-angularjs/
$setPristine will only clear the variables not the form. To clear the form set their values to blank strings
<script type="text/javascript">
function CommentController($scope) {
var defaultForm = {
author : "",
email : "",
comment: ""
};
$scope.postComments = function(comment){
//make the record pristine
$scope.commentForm.$setPristine();
$scope.comment = defaultForm;
};
}
</script>
Clear topRiskDTO
Looking at your example, seems that clearing topRiskDTO will give you this result.
for instance:
$scope.submit = function(){
// ...
// The submit logic
// When done, Clear topRiskDTO object
for (var key in $scope.topRiskDTO)
{
delete $scope.topRiskDTO[key];
}
};
You have to manually reset the data. See this website for more info.
You also have to call
$form.$setPristine()
To clear all the css classes.
i'm trying to do a form with validations using angularjs and so far i did a good job. But when i commit my reset button all the fields reset except for the error messages i get from my validation part. How can i get rid of all the fields and error messages when i reset my form.
This is how it is when i press my reset button
this is my code
<div class="page-header"><center><h2>Give us your Feedback</h2></center></div>
<!-- pass in the variable if our form is valid or invalid -->
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$dirty }">
<label>Name*</label>
<input type="text" name="name" class="item-input-wrapper form-control" ng-model="user.name" required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine " class="help-block">
<font color="#009ACD">You name is required.</font>
</p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$dirty }">
<label>Email</label>
<input type="email" name="email" class="item-input-wrapper form-control" ng-model="user.email" required >
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">
<font color="#009ACD">Enter a valid email.</font>
</p>
</div>
<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$dirty }">
<label>Description</label>
<input type="text" name="username" class="item-input-wrapper form-control" ng-model="user.username" ng-minlength="5" ng-maxlength="60" required>
<font color="white">
<p ng-show="userForm.username.$error.minlength" class="help-block">
<font color="#009ACD">Description is too short.</font>
</p>
<p ng-show="userForm.username.$error.maxlength" class="help-block">
<font color="#009ACD">Description is too long.</font>
</p>
</font>
</div>
<div class="col"style="text-align: center">
<button align="left"class="button button-block button-reset"style="display: inline-block;width:100px;text-align:center "
type="reset"
ng-click="reset()" padding-top="true"
>
Reset
</button>
<button class="button button-block button-positive" style="display: inline-block;width:100px "
ng-click="submit()"
padding-top="true"
>
Submit
</button>
</div>
</form>
</div>
My controller
.controller('ContactCtrl', function($scope,$state,$ionicPopup, $timeout) {
$scope.showfeedback = function() {
$state.go('app.sfeedback');
};
$scope.submitForm = function(isValid) {
$scope.submitted = true;
// check to make sure the form is completely valid
if (!isValid) {
var alertPopup = $ionicPopup.alert({
title: 'Invalid data entered!',
});
} else {
var alertPopup = $ionicPopup.alert({
title: 'Feedback submitted',
});
}
};
$scope.reset = function() {
var original = $scope.user;
$scope.user= angular.copy(original)
$scope.userForm.$setPristine()
};
})
var original = $scope.user;
when resetting :
$scope.user= angular.copy(original);
$scope.userForm.$setPristine();
remove
type='reset' in <button>
here is the Angular Documentation for form controllers.
Use the following to reset dirty state
$scope.form.$setPristine();
Use the following to reset to clear validation
$scope.form.$setValidity();
There's API documentation on the FormController.
This allowed me to find that there's other methods to call such as:
$setUntouched() - which is a function I was using if the user has focused on the field, and then left the field, this clears this feature when you run it.
I created a simple form reset function which you can use too.
// Set the following in your controller for the form/page.
// Allows you to set default form values on fields.
$scope.defaultFormData = { username : 'Bob'}
// Save a copy of the defaultFormData
$scope.resetCopy = angular.copy($scope.defaultFormData);
// Create a method to reset the form back to it's original state.
$scope.resetForm = function() {
// Set the field values back to the original default values
$scope.defaultFormData = angular.copy($scope.resetCopy);
$scope.myForm.$setPristine();
$scope.myForm.$setValidity();
$scope.myForm.$setUntouched();
// in my case I had to call $apply to refresh the page, you may also need this.
$scope.$apply();
}
In your form, this simple setup will allow you to reset the form
<form ng-submit="doSomethingOnSubmit()" name="myForm">
<input type="text" name="username" ng-model="username" ng-required />
<input type="password" name="password" ng-model="password" ng-required />
<button type="button" ng-click="resetForm()">Reset</button>
<button type="submit">Log In</button>
</form>
I went with...
$scope.form.$setPristine();
$scope.form.$error = {};
Feels hacky... but a lot about angular does.
Besides... this was the only thing that worked.
I had the same problem and used the following code to completely reset the form :
$scope.resetForm = function(){
// reset your model data
$scope.user = ...
// reset all errors
for (var att in $scope.userForm.$error) {
if ($scope.userForm.$error.hasOwnProperty(att)) {
$scope.userForm.$setValidity(att, true);
}
}
// reset validation's state
$scope.userForm.$setPristine(true);
};
To me using $setPristine to reset the form is a hack.
The real solution is to keep it like it should be:
<button type="reset" ng-click="reset()"></button>
then in angular:
var original = angular.copy($scope.user);
$scope.reset = function() {
$scope.user = angular.copy(original);
};
and that's it.
Use this
<button type="button" ng-click='resetForm()'>Reset</button>
In Controller
$scope.resetForm = function(){
$scope.userForm.$dirty = false;
$scope.userForm.$pristine = true;
$scope.userForm.$submitted = false;
};
Its working for me
In case you don't have a master (dynamic models from server), and you want to reset the form but only the binded part of the model you can use this snippet:
function resetForm(form){
_.forEach(form, function(elem){
if(elem !== undefined && elem.$modelValue !== undefined){
elem.$viewValue = null;
elem.$commitViewValue();
}
});
}
And then you can use it with a standard reset button like so:
<button type="reset" ng-click="resetForm(MyForm);MyForm.$setValidity();">reset</button>
Give us your Feedback
<!-- pass in the variable if our form is valid or invalid -->
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$dirty }">
<label>Name*</label>
<input type="text" name="name" class="item-input-wrapper form-control" ng-model="user.name" required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine " class="help-block"><font color="#009ACD">You name is required.</font></p>
</div>
<!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$dirty }">
<label>Email</label>
<input type="email" name="email" class="item-input-wrapper form-control" ng-model="user.email" required >
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block"><font color="#009ACD">Enter a valid email.</font></p>
</div>
<!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$dirty }">
<label>Description</label>
<input type="text" name="username" class="item-input-wrapper form-control" ng-model="user.username" ng-minlength="5" ng-maxlength="60" required>
<font color="white"><p ng-show="userForm.username.$error.minlength" class="help-block"><font color="#009ACD">Description is too short.</font></p>
<p ng-show="userForm.username.$error.maxlength" class="help-block"><font color="#009ACD">Description is too long.</font></p>
</div>
<div class="col"style="text-align: center">
<button align="left"class="button button-block button-reset"style="display: inline-block;width:100px;text-align:center "
type="reset"
ng-click="reset()"padding-top="true">Reset</button>
<button class="button button-block button-positive" style="display: inline-block; width:100px" ng-click="submit()"padding-top="true">Submit</button>
</div>
</form>
I kept the type="reset" in my button. What I did was the ng-click="resetForm(userForm)" (using userFrom to match your example) and the controller defines resetForm() as
scope.resetForm = function(controller) {
controller.$commitViewValue();
controller.$setPristine();
};
Here is what happens:
When the reset button is clicked, it will bring back the original values as specified by the value attribute on the input
The $commitViewValue() will force the write of whatever is on the view presently to the $modelValue of each field (no need to iterate manually), without this the last $modelValue would still be stored rather than reset.
The $setPristine() will reset any other validation and submitted fields.
In my angular-bootstrap-validator I already had the FormController as such I didn't need to pass in the form itself.
In My Form
<form angular-validator-submit="submitReview()" name="formReview" novalidate angular-validator>
<input type="text" name="Rating" validate-on="Rating" class="form-control"
ng-model="Review.Rating" required-message="'Enter Rating'" required>
<button type="button" ng-click="reset()">Cancel</button>
</form>
app.controller('AddReview', function ($scope) {
$scope.reset= function () {
$scope.formReview.reset()
};
});
only need to call $scope.formReview.reset() where formReview is my form name.
My form is inside another scope so my solution need to use $$postDigest
$scope.$$postDigest(function() {
$scope.form.$error = {};
});
To reset the validations we have to do two things:
clear the fields
Add the following:
$scope.programCreateFrm.$dirty = false;
$scope.programCreateFrm.$pristine = true;
$scope.programCreateFrm.$submitted = false;
programCreateFrm is the name of the form.
For example:
<form name="programCreateFrm" ng-submit="programCreateFrm.$valid && createProgram(programs)" novalidate>
This code is working for me.
SO basically I create a view like so (I create it like this as I need it to act as a pop up)
Application.container = Ember.ContainerView.create();
Application.container.append();
Application.loginOverlay = Application.LoginOverlayView.create({
});
Application.childViews = Application.container.get('childViews');
Application.childViews.pushObject(Application.loginOverlay);
I have a view that looks like this
Application.LoginOverlayView = Ember.View.extend({
templateName: 'view/loginOverlay',
password: null,
logBackIn: function (password) {
console.log('logBackIn');
},
closeOverlay: function () {
console.log('closeOverlay');
},
username: function () {
return Application.user.get('username');
}.property().volatile()
});
Here's my template
<div id="login-overlay" class="overlay">
<section>
<form id="login_form">
<div class="control-group">
<label class="control-label" for="username">{{localise _username}}: {{username}}</label>
</div>
<div class="control-group">
<label class="control-label" for="reenter-password">{{localise _password}}</label>
<div class="controls">
{{view Ember.TextField name="reenter-password" elementId="reenter-password" valueBinding="password" placeholder="password" type="password"}}
</div>
</div>
<div class="control-group">
<input type="button" value="{{localise _login}}" class="btn btn-success" {{action 'logBackIn' password target="view"}} {{bindAttr disabled=busy}} />
<input type="button" value="{{localise _cancel}}" class="btn btn-danger" {{action 'closeOverlay' target="view"}} {{bindAttr disabled=busy}} />
</div>
</form>
</section>
</div>
The actions on the view are doing anything when clicked.
I'm using an old verion of Ember - v1.0.0-rc.7-9-g7398406
Any ideas?
*EDIT*
I did try it with the actions hash like so
Application.LoginOverlayView = Ember.View.extend({
// layoutName: 'view/loginOverlay',
templateName: 'view/loginOverlay',
password: null,
init: function () {
console.log('LoginOverlayView');
this._super();
},
actions: {
logBackIn: function (password) {
console.log('logBackIn');
},
closeOverlay: function () {
console.log('closeOverlay');
Application.removePasswordOverlay();
},
username: function () {
console.log('username');
return Application.user.get('username');
}.property().volatile()
}
});
but no joy. Also I added the init to make sure it was being created and it was, the log is being called
Another thing to add is that I'm not getting any feedback when I click the buttons. I'm not getting any kind of error or anything.
I have put up a snippet of my MVC4 code here. I would like the "minus" button to remove the row it belongs to, then goes through the array and adjust the input names to be sequential. I think I will need it to be sequential to work with MVC4 model binding.
My problem is, how do I identify which button has just been clicked, and which object in the array it belongs to? Any ideas please? I'm completely new to knockout so I'm not even sure if this is the best way to do it.
This is my viewmodel:
function ViewModel() {
this.breeders = ko.observableArray([{
keyName: ko.observable("Breeders[0].Key"),
valueName: ko.observable("Breeders[0].Value"),
canAdd: ko.observable(true),
canRemove: ko.observable(true)
}]);
this.addRow = function () {
var next = this.breeders().length;
this.breeders.push({
keyName: ko.observable("Breeders[" + next.toString() + "].Key"),
valueName: ko.observable("Breeders[" + next.toString() + "].Value"),
canAdd: ko.observable(true),
canRemove: ko.observable(true)
});
};
this.removeRow = function () {
};
}
And this is my markup:
<div class="form-group">
<div id="breedersFormsContainer" data-bind="template: {name: 'breederForm', foreach: breeders}"></div>
</div>
<script type="text/html" id="breederForm">
<div class="col-lg-offset-3">
<span class="col-lg-1 control-label">Reg: </span><span class="col-lg-2"><input data-bind="attr: {name: keyName}" type="text" class="form-control" /></span>
<span class="col-lg-1 control-label">Name: </span><span class="col-lg-6"><input data-bind="attr: {name: valueName}" type="text" class="form-control" /></span>
<button type="button" class="btn btn-default" data-bind="enable: canRemove"><span class="glyphicon glyphicon-minus">-</span></button>
<button type="button" class="btn btn-default" data-bind="enable: canAdd, click: $parent.addRow.bind($parent)"><span class="glyphicon glyphicon-plus">+</span></button>
</div>
</script>
If you have bound the click handler to the button, you can do the following
this.removeRow = function (data) {
yourObservableArray.remove(data);
};
data will be a reference to the object bound to the current row
I am using HTML5 validation in my form which is like this,
<script type="text/x-handlebars" id="project">
<div class="row">
<div class="span6">
<div class="well well-small">
<p style="text-align: center">
You can create a new Project by filling this simple form.
</p>
<p style="text-align: center"> Project Name should be minimum 10 characters & There's no limit on
Project Description.
</p>
</div>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="projectname">Project Name: </label>
<div class="controls">
{{!view App.TextFieldEmpty}}
<input type="text" name="projectname" id="projectname" required title="Project Name is Required!" pattern="[A-z ]{10,}" placeholder="Enter Project Name"/>
</div>
</div>
<div class="control-group">
<label class="control-label" for="projectdesc">Project Description:</label>
<div class="controls">
<textarea rows="3" id="projectdesc" name="projectdesc" placeholder="Enter Project Desc"
required="Description Required"></textarea>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn" {{action 'createNew'}}>Add Project</button>
</div>
</div>
</form>
</div>
</div>
</script>
And here's what I have tried to do in App.js,
App.ProjectController = Ember.ArrayController.extend({
actions : {
createNew : function() {
if (!("#project form.form-horizontal") === "") {
App.Project.createNew();
}
}
}
});
App.ProjectRoute = Ember.Route.extend({
});
App.Project.reopenClass({
createNew : function() {
dataString = {
'projectname' : $("#projectname").val(),
'projectdesc' : $("#projectdesc").val()
};
console.log('check');
$.ajax({
type : "POST",
url : "http://ankur.local/users/createNewProject",
data : dataString,
dataType : "json",
success : function(data) {
console.log('success');
}
});
return false;
}
});
As you can see in the actions, I am trying to check if form is not empty then do a Ajax POST. But the problem I am encountering is even if the form is not empty, the button doesn't do anything.
Moreover, if I am including the whole form, it will check checkboxes as well? (I want to have one as well)
What I can do to make sure that user doesn't submit empty form?
This is more of a JS/jQuery question than an Ember one. You should look at the jQuery val() function.
You should validate your form inputs in your view, where you can access the <input elements. Furthermore (!("#project form.form-horizontal") === "") is missing the jQuery selector $.
App.ProjectView = Ember.View.extend({
actions : {
createNew : function() {
if (!(this.$("#projectname").val() === "")) {
App.Project.createNew();
}
}
}
});
There might be some other kinks in your code, it would be helpful if you could put together a jsFiddle - that way it makes it much easier for us to help you and you.
Okay I am going to answer my own question & it seems to be working.
Here's what I did:
App.ProjectController = Ember.ArrayController.extend({
actions : {
createNew : function(event) {
$(":text, :file, :checkbox, select, textarea").each(function() {
if ($(this).val() === "") {
alert("Empty Fields!!");
} else {
App.Project.createNew();
event.preventDefault();
}
});
}
}
});