how to validate particular input field using angularjs? - html

I am trying to validate some input fields using angularJS. I found some example. But they are validating entire form.
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" ng-model='name' ng-required="true" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
</form>
</div>
and controller code is
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name=undefined;
$scope.preview = function(){
alert("Previewed");
};
$scope.update = function(){
alert("Updated");
}
});
The above code validating the fields based on form name. But I wanted to know is there any way to validate that particular input field ?

DEMO
Yes you can, you must specify a name for the input like
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" name='name' ng-model='name' ng-required="true" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
</form>
</div>
then you can check if the name is valid with myForm.name.$valid

Check out the fiddle here.
Just add a name to the input filed and follow the same as you did to the form.
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" ng-model='name' ng-required="true" name="txtName" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
<div>Status of name: <span style="color: blue">{{myform.txtName.$valid}}</span></div>
</form>
</div>
JS:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.name = undefined;
$scope.preview = function () {
alert("Previewed");
};
$scope.update = function () {
alert("Updated");
}
});

Related

I want to set ng model's value with value attribute's value

<input type="text" value="{{id}}" class="form-control" id="pid" ng-model="user.id" readonly />
if text box's value is 1 i want to set the user.id value as 1
You can add dynamic attribute binding, using angular's directive.
<div ng-app="myApp" ng-controller="ctrl">
<input type="text" ng-attr-value="{{title}}" class="form-control" id="pid" ng-model="title" readonly />
</div>
JS
var app = angular.module('myApp', []);
function ctrl($scope){
$scope.title = "I 'm a tooltip!";
}
Fiddle
Try Following code,
var app = angular.module("app", []);
app.controller("InputController", function($scope) {
$scope.user={"id":1};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="InputController">
<input type="text" value="{{user.id}}" class="form-control" id="pid" ng-model="user.id" readonly />
</body>

Getting text from html scope

.controller('LoginCtrl', function($scope, $rootScope, $http, $state) {
window.localStorage.removeItem("loggedIn");
if(window.localStorage.getItem("loggedIn") == undefined) {
$scope.doLogin = function() {
var username = $scope.fName + " " + $scope.lName;
console.log(username);
//store login information
window.localStorage.setItem("username", username);
window.localStorage.setItem("password", $scope.password);
window.localStorage.setItem("loggedIn", true);
$http.post('http://localhost:8000/login',{
userName: window.localStorage.getItem("username"),
password: window.localStorage.getItem("password"),
token: $rootScope.devToken,
platform: ionic.Platform.platform()
});
alert("Login Success");
$state.go('main');
};
} else {
alert("Login Success");
$state.go('main');
}
})
<ion-content ng-controller="LoginCtrl">
<form ng-submit="doLogin()" style="display: block; margin: 100px">
<div class="list">
<label class="item item-input">
<input type="text" ng-model="fName" placeholder="First Name">
</label>
<label class="item item-input">
<input type="text" ng-model="lName" placeholder="Last Name">
</label>
<label class="item item-input">
<input type="password" ng-model="password" placeholder="Password" style="text-align: center">
</label>
<label class="item">
<button class="button button-block button-positive" type="submit">Register</button>
</label>
</div>
</form>
</ion-content>
I am trying to get the text from the html field fName and lName using $scope.fName because fName is a ng-model. How come it is returning undefined? I have the controllers set properly. I just can't figure out why username is outputting undefined? I am trying to load the app up at login.html and then once logged in, it will change the state to home.html. I could really use some help doing this.
The ion-content creates its own child scope. Try declaring a main scope object in your controller:
.controller('LoginCtrl', function($scope, $rootScope, $http, $state) {
$scope.data = {}
In your template:
<input type="text" ng-model="data.fName" placeholder="First Name">
In your login submit:
var username = $scope.data.fName + " " + $scope.data.lName;
You don't have validation in place to check whether the values are actually filled or not. The scope is not populated on initialization.
If you hit submit before adding anything there is no way those values can be populated and hence they are undefined.
Do something like this in submit button.
<button class="button button-block button-positive"
type="submit" ng-disabled="!fName||!lName">Register
</button>
Good Luck.
The code implementation is found here.
https://codepen.io/anon/pen/YGzxVz
http://ionicframework.com/docs/components/#toggle
i hope this works for you. A little change with CSS will do the trick

Submit input on enter in AngularJS form

I'm trying to complete or submit an input on enter press instead of clicking a submit button. Is this possible purely through a directive? Or must I add some JS?
Here's my input:
<input type="text" ng-model='main.input' placeholder='some text' required=''/>
Use ng-keyup native directive on the input and fire up ng-submit on the form:
<form ng-submit="submitFunc()">
<input type="text" ng-model='main.input' placeholder='some text' required='' ng-keyup="$event.keyCode == 13 && submitFunc()"/>
</form>
You can use ng-submit to submit your form on enter button click. See the example below,
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope',
function($scope) {
$scope.text = 'hello';
$scope.submit = function() {
if ($scope.text) {
$scope.enterText = this.text;
$scope.text = '';
}
};
}
]);
</script>
<div ng-app="submitExample">
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{enterText}}</pre>
</form>
</div>

Putting value to hidden input and then getting it in POST variable

I am trying to get an input value with AngularJS from input field to another hidden input field (in another form in the same page) so I can transmit it later if user presses submit on the other form.
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
//down the code...
<form name="whatever" method="post">
<input type="hidden" ng-bind="name" value="">
</form>
</div>
When I inspect the code after I put data in the visible input field all looks fine - so when I change the data inside the visible input I can see it in the hidden input too but I can't see it in the POST variable after I submit the form - I guess it's because it doesn't change the value field in the hidden input just what between the and .
How can I get this to work so that I change the value of an hidden input - but not what between the opening and closing input field?
Just Replace ng-bind with ng-value like:
<input type="hidden" ng-value="name">
(Credit to Himmet Avsar)
I see you answered yourself already. Anyway you should go for more "angular way" when handling your forms, letting angular do the "posting". For example:
HTML template
<body ng-controller="MainCtrl">
<form name="form1"
ng-submit="submit()">
Name: <input type="text"
class="form-control"
name="name"
ng-model="user.name"
required>
<div class="alert alert-warning"
ng-show="form1.name.$error.required">
Required field
</div>
<input type="submit"
class="btn btn-primary"
value="submit">
</form>
<div class="alert"
ng-class="{ 'alert-success': response.status === 200, 'alert-danger': response.status !== 200 }"
ng-show="response !== null">
DATA: {{ response.data }}<br>
HTTP {{ response.status }} {{ response.statusText }}
</div>
<hr>
<form name="form2" ng-submit="submit()">
Name: <input type="text"
class="form-control"
ng-model="user.name">
Age: <input type="number"
class="form-control"
min="1"
max="100"
ng-model="user.age">
<input type="submit"
class="btn btn-primary"
value="submit" disabled>
</form>
</body>
JavaScript
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.user = {};
$scope.response = null;
$scope.submit = function() {
$scope.response = null;
$http({
method: 'POST',
url: 'http://jsonplaceholder.typifcode.com/posts',
data: $scope.user,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
$scope.response = response;
}).catch(function (response) {
$scope.response = response;
});
};
});
You'll get something like
Related plunker here http://plnkr.co/edit/M7zQzp

google.script.run and form with input type=file produce string "FileUpload" not a blob

I use HTMLServices with google.script.run calls with form in args and i try to get the image from my form input file field and store it in my drive.
I get the value of all the fields correctly except the photodata field.
photodata contain the string "FileUpload" instead of a blob.
I have tested with .getBlob for the same result.
Server Side :
function setUsager(form) {
var blob = form.photodata;
Logger.log(Utilities.jsonStingify(blob);
DriveApp.getFolderById('0B2DdOMvW2Q84N0s4a21LM05wbms').createFile(form.usagerId,blob);
obj = new {};
obj.photo = file.getUrl();
return obj;
}
on click Handler
function onUsagerEditFormSubmit() {
loading(true);
var form = this.parentNode;
google.script.run.withSuccessHandler(showUsager)
.withFailureHandler(showError)
.setUsager(form);
}
And the form :
<form name="usager-edit" id="usager-edit" method='post' enctype="multipart/form-data">
<div class="hidden">
<input type="text" name="type" id="type" value="USAGER" readonly="readonly" />
<input type="text" name="usagerId" id="usagerId" readonly="readonly" />
</div>
<div class="field-container">
<label for="nom">Nom</label>
<input type="text" name="nom" id="nom">
</div>
<div class="field-container">
<label for="prenom">Prenom</label>
<input type="text" name="prenom" id="prenom">
</div>
<div class="field-container">
<label for="photo">Photo</label>
<input class="file" type="file" name="photodata" id="photodata" accept='image/*'>
<div id="prev-photo" name="prev-photo"></div>
<div class="clear"></div>
</div>
<input class="myButton" onClick="onUsagerEditFormSubmit" type="button" name="save" id="save-button" value="Sauvegarder" />
</form>
You are using the wrong createFile method overload.
You are using createFile(name, content), when you should use createFile(blob).
...
var file = DriveApp.getFolderById('****************************').createFile(blob);
...
You must define file in order to make: obj.photo = file.getUrl();.
Also you can change the following:
...
<input class="myButton" onClick="onUsagerEditFormSubmit" type="button" name="save" id="save-button" value="Sauvegarder" />
...
by:
...
<input class="myButton" onClick="onUsagerEditFormSubmit(this.parentNode)" type="button" name="save" id="save-button" value="Sauvegarder" />
...
and
function onUsagerEditFormSubmit() {
loading(true);
var form = this.parentNode;
google.script.run.withSuccessHandler(showUsager)
.withFailureHandler(showError)
.setUsager(form);
}
by:
function onUsagerEditFormSubmit(form) {
loading(true);
google.script.run.withSuccessHandler(showUsager)
.withFailureHandler(showError)
.setUsager(form);
}
Slight changes:
...
Logger.log(Utilities.jsonStingify(blob);
...
obj = new {};
...
by:
...
Logger.log(Utilities.jsonStringify(blob));
...
var obj = {};
...