How to check the disabled button is true/false ? in angularjs - javascript

Hi guys is there any ways on how to check the disable button ??
Here is my button disabled code inside (index.html):
ng-disabled="epUpdateAllForm.$invalid || epUpdateAllForm.$pending"
In controller :
if((($scope.epUpdateAllForm.$invalid) || ($scope.epUpdateAllForm.$pending)) == true) {
console.log("Some mandatory fields is not completed");
}

You can check button is disabled using angular.element(..).prop()
var target = angular.element(document.getElementById("#buttonIdHere"));
if (target.prop('disabled')) {
// Button is disabled
}
Option 2
Watch for yourForm.$valid, yourForm.$invalid & yourForm.$pending in your controller
var isFormValid = false;
$scope.$watch('yourForm.$valid', function(newVal) {
isFormValid = true;
});
$scope.$watch('yourForm.$invalid', function(newVal) {
isFormValid = false;
});
$scope.$watch('yourForm.$pending', function(newVal) {
isFormValid = false;
});
And simply check if isFromValid is true before executing your submission logic.

If you need to check the logic of submit, then you can pass a form object to the handler submit.
Example on jsfiddle.
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.submit = function(form) {
if (form.$invalid)
console.warn('Form is invalid');
else
console.log('Form is valid');
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController as vm">
<form name="testForm">
<label> This field is required
<input type="text" name="testInput" ng-model="myInput" required>
</label>
<button ng-click="submit(testForm)">
Submit
</button>
</form>
</div>
</div>

Related

Make invalid form immediately after loading

I have a simple form written in AngularJS.
I would like to make the form invalid immediately after loading. Unfortunately $scope.myForm.$valid = false; doesn't want work. Do you have any other technique to do it? It is important for me as I want to let user click the button only when he/she choose at least on checkbox. Now you can submit the form always after loading the form.
<form name="myForm" ng-submit="myForm.$valid">
<input type="checkbox" ng-model="obj.first" ng-change="onChange()" /> First <br />
<input type="checkbox" ng-model="obj.second" ng-change="onChange()"/>Second <br />
<input type="checkbox" ng-model="obj.third" ng-change="onChange()"/> Third <br>
<button type="submit" ng-disabled="!myForm.$valid" ng-click="click()">test</button> <br>
</form>
$scope.myForm = {};
$scope.myForm.$valid = false;
$scope.click=function () {
console.log('-------------2', $scope.myForm);
};
$scope.onChange=function () {
console.log('before:', $scope.myForm);
var isValid = false;
angular.forEach($scope.obj, function(value, key) {
if(value == true){
isValid=true;
}
console.log(key + ': ' + value);
});
if(!isValid){
$scope.myForm.$valid = false;
$scope.myForm.$error.checkBoxes = {
isChecked: false
};
}
console.log('after:', $scope.myForm);
}
So this is my final solution, the form in the scope has a function called $setValidity() where we can change the validity state, and notify the form. Refer here, so I check if any of the checkboxes are having true value, then I set the value for one checkbox alone as true, if not then one of the checkboxes with name one is set to $valid = false, thus the entire form will be invalid, please go through my code for the implementation of the solution!
JSFiddle Demo
JS:
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope) {
$scope.onChange = function() {
if ($scope.obj) {
if ($scope.obj.first || $scope.obj.second || $scope.obj.third) {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", true);
} else {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
}
} else {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
}
}
});
Try this in your submit button. hope it works
data-ng-disabled="myForm.$submitted || myForm.$invalid && !myForm.$pristine"

OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript

I have a form which validates password null/blank or not using onblur. And I use a submit button to submit the form. However the submit button needs to be clicked twice before to work. It does not work on the first click after something has been filled in the password box. Below is the code.
With respect to Jquery, I require solution in pure Javascript.
I have tried onkeyup, but that is not a good solution as it will put strain on system, and server (for ajax).
<!DOCTYPE html>
<html>
<body>
<script>
var error_user_password = false;
function checkpw(){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall() {
checkpw()
if(error_user_password == false) {
return false;
} else {
return true
}
}
</script>
</body>
<form id="joinform" method="post" name="joinform" action="#hello" onsubmit="return submitall()" >
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password" onblur="checkpw()" />
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
</html>
OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript
This happens because the blur event is captured from the onblur event handler and not bubbled to the form submit button.
A full javaScript solution is based on:
addEventListener
activeElement: inside the blur event I check after 10 milliseconds if the submit button get the focus.
My snippet:
var error_user_password = false;
function checkpw(ele, e){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_password == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_password').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>

JS wont recognize a variable within angular controller object

Im trying to create a simple login verification, however the validation function seizes to function when the validation comparison begins, and the console sais that the variable "userName is not defined" although it clearly is.
Can enyone tell me what am i defining wrong?
the angular controller code:
var app = angular.module("LoginApp", []);
app.controller("LoginController", function ($http) {
this.userName = "";
this.password = "";
this.userNameValid = true;
this.passwordValid = true;
/*submit the form*/
this.submit = function () {
alert("submit");
this.validate();
};
/* make sure user name and password has been inserted*/
this.validate = function () {
alert("validate");
var result = true;
this.userNameValid = true;
this.passwordValid = true;
if (this.userName == "") {
alert("username="+userName);
this.userNameValid = false;
result = false;
}
if (this.password == "") {
this.passwordValid = false;
result = false;
}
alert("validuserNameValid==" + userNameValid + " passwordValid==" + passwordValid);
return result;
};
});
the HTML form:
<body ng-app="LoginApp" ng-controller="LoginController as LoginController">
<form role="form" novalidate name="loginForm" ng-submit="LoginController.submit()">
<div id="loginDetails">
<div class="form-group">
<label for="user"> User Name:</label>
<input type="text" id="user" class="form-control" ng-model="LoginController.userName" required />
<span ng-show="LoginController.userNameValid==false" class="alert-danger">field is requiered</span>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" id="password" class="form-control" ng-model="LoginController.password" required />
<span ng-show="LoginController.passwordValid==false" class="alert-danger">field is requiered</span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
{{"entered information:" +"\n"+LoginController.userName+" "+ LoginController.password}}
</div>
</div>
</form>
</body>
the log:
Error: userName is not defined
this.validate#http://localhost:39191/login.js:23:13
this.submit#http://localhost:39191/login.js:11:9
anonymous/fn#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js line 231 > Function:2:292
b#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:126:19
Kc[b]</<.compile/</</e#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:274:195
uf/this.$get</m.prototype.$eval#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:103
uf/this.$get</m.prototype.$apply#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:145:335
Kc[b]</<.compile/</<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:274:245
Rf#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:37:31
Qf/d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js:36:486
Always use this judiciously. I would recommend you to store the reference of this in variable then use it wherever required.
var app = angular.module("LoginApp", []);
app.controller("LoginController", function ($http) {
//Store the reference of this in a variable
var lc = this;
//Use the stored refrence
lc.userName = "";
/* make sure user name and password has been inserted*/
lc.validate = function () {
if (lc.userName == "") {
alert("username="+userName);
lc.userNameValid = false;
result = false;
}
};
});
inside your alert boxes you have not mentioned this.userName try removing the alert boxes or change them.

Validate the input field for existing item in object array?

in my todo list i dont want user to input same todos again again...
but my problem is, when i enter something for example (test) first time and than i enter (test2) and than i enter (test) again, so its taking a value.... how to validate properly....
fiddle
https://jsfiddle.net/LaL7h6Lv/1/
html
<div ng-app="todoApp" ng-controller="mainCtrl">
<ul>
<li ng-repeat="todoItem in todoItems">{{todoItem.name}}</li>
</ul>
<form ng-submit="addItem()">
<input type="text" ng-model="newItem">
<input type="submit" name="go">
</form>
</div>
angularjs
angular.module("todoApp", [])
.controller('mainCtrl', ['$scope', function($scope){
$scope.todoItems = [{'name' : 'akshay'}];
$scope.test = false;
$scope.addItem = function(){
if($scope.newItem){
$scope.checkRepeatTodo();
if($scope.test == true){
$scope.todoItems.push({'name':$scope.newItem});
$scope.newItem = '';
}else{
alert('same todo');
$scope.test = false;
}
}else{
alert('fill the form');
}
};
$scope.checkRepeatTodo = function(){
$scope.todoItems.filter(function(item){
if($scope.newItem === item.name){
$scope.test = false;
}else{
$scope.test = true;
}
});
};
}]);
The issue is with the $scope.test value, you override the value to true when it filters down the 3rd item.
See the Working fiddle
Alternative:
Make a javascript function rather than one in $scope and call that function return if its a valid entry or not.
This eliminates the need to have $scope.test and $scope.checkRepeatTodo as they do nothing of importance.
function checkRepeatTodo() {
var valid = true;
$scope.todoItems.filter(function(item){
if($scope.newItem === item.name){
return valid = false;
}
});
return valid;
};
And use the same as:
if(checkRepeatTodo()){
$scope.todoItems.push({'name':$scope.newItem});
$scope.newItem = '';
}
else{
alert('same todo');
}
Demo here

How to change value of variable in $scope on-click?

I would like to change the value of $scope.complete to false when the user clicks a particular URL. Is this possible to do in Angular?
I show credit card form to the user based on this variable. On first page load the variable is true/false based on value coming from server side that suggests whether there is a credit card on file or not.
If there is a credit card on file then I want to have a change url. Which, when clicked, would change the value of $scope.complete to false and the credit card form would show up.
This is my code at the moment:
JS
$scope.complete = false;
djangoAuth.profile().then(function(data){
$scope.model = data;
if ($scope.model.profile.stripe_id.length <= 0)
$scope.complete = false;
else
$scope.complete = true;
});
html:
<div ng-if="complete == false">
<!--show form-->
</div>
<div ng-if="complete == true">
Credit card already on file. Change?
</div>
You can bind a function to ng-cick and have the function change the value of the property:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.complete = true;
$scope.change = function() {
$scope.complete = false;
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-show="complete == false">
form here
</div>
<div ng-show="complete == true">
Credit card already on file. Change?
</div>
</div>
See this fiddle showing ng-click on archive()
http://jsfiddle.net/dakra/U3pVM
archive
$scope.archive = function() {
var oldTodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.done) $scope.todos.push(todo);
});
};
This isn't my fiddle, but shows how to use it.
Documentation is also at:
https://docs.angularjs.org/api/ngTouch/directive/ngClick
JS
$scope.complete = false;
djangoAuth.profile().then(function(data){
$scope.model = data;
// default scope
$scope.complete = true;
$scope.change = function(){
$scope.complete = true;
}
if ($scope.model.profile.stripe_id.length <= 0)
$scope.complete = false;
else
$scope.complete = true;
});
html:
<div ng-if="complete == false">
<!--show form-->
</div>
<div ng-if="complete == true">
Credit card already on file. <a ng-click="change()" ng-href="#">Change?</a>
</div>

Categories