Very Basic Example - Enable or Disable a button - javascript

I have this very basic example. This should work in a form for multiple inputs as well.
I want a form without any required parameters. But I only want to enable the button if at least one of them is not empty.
$pristine almost works. The problem is that if I type something and delete it the button remains enabled.
Basically,
If all fields are empty -> button disabled
Else if at least one not empty -> button enabled
function ctrl($scope){
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<form name="myForm" ng-controller="ctrl">
<input type="text" ng-model="name" name='myName' ng-model='myName'/>
<span>{{name}}</span>
<input type="submit" value="Submit" ng-disabled="myForm.$pristine" />
{{myForm.$pristine}}
</form>
</div>

Pristine checks whether the input field is touched or not. That's why it remains enabled after you deleted your input. Check on valid and provide some condition. Or use pattern and regex.

With `required`:
function ctrl($scope) {
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<form name="myForm" ng-controller="ctrl">
<input type="text" ng-model="name" name='myName' ng-model='myName' required/>
<span>{{name}}</span>
<input type="submit" value="Submit" ng-disabled="myForm.$invalid"/>
</form>
</div>
Without required using controller:
function ctrl($scope) {
$scope.isDisable = true;
$scope.validate = function(){
if($scope.name == undefined || $scope.name == ""){
$scope.isDisable = true;
} else {
$scope.isDisable = false;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<form name="myForm" ng-controller="ctrl">
<input type="text" ng-model="name" name='myName' ng-model='myName' ng-keyup = "validate()"/>
<span>{{name}}</span>
<input type="submit" value="Submit" ng-disabled="isDisable"/>
</form>
</div>
Another way using `name.length`:
function ctrl($scope) {
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<form name="myForm" ng-controller="ctrl">
<input type="text" ng-model="name" name='myName'/>
<span>{{name}}</span>
<input type="submit" value="Submit" ng-disabled="!name.length"/>{{name.length}}
</form>
</div>
Note: If you don't want to use HTML5 validation that you can mark your form novalidate.

This is naive way, but you can just use ng-model of each input in ng-disabled
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<form name="myForm" ng-controller="ctrl">
<input type="text" ng-model="name" name='myName' />
<input type="text" ng-model="fName" name='FirstName'/>
<span>{{name}}</span>
<input type="submit" value="Submit" ng-disabled="!(name || fName)" />
{{myForm.$pristine}}
</form>
</div>
Also, your code has 2 ng-model for the same input

Use disabled="!name.length" instead of ng-disabled="myForm.$pristine".
This will solve your issue. Below is working code:
function ctrl($scope) {
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<form name="myForm" ng-controller="ctrl">
<input type="text" ng-model="name" name='myName' ng-model='myName' />
<span>{{name}}</span>
<input type="submit" value="Submit" ng-disabled="!name.length" />
{{myForm.myName.$pristine}}
</form>
</div>

Related

How can I tell the browser to empty a field by using JQuery and then call the function?

I inserted a form on a html page, which contains several fields the user is supposed to fill ("name", "surname", a textarea, and so on); I then added a button and assigned the id Click to it:
<input type="button" name="button" value="Click" id="cliccami">
I linked the html page to a JQuery file.
By using JQuery I want to add a function clearAll which clears all the fields in the form when the user clicks on the button. I want to use another function main which calls the function clearAll when the button is clicked, as in the following:
function main() {
$("form").on("button", clearAll);
}
How can I write the function clearAll (to empty the fields in the form) by using JQuery?
Inside the function you can target the closest() form of this element to find all the elements to clear them like the following way:
function main() {
$("form").on("click", "#cliccami", clearAll);
}
function clearAll() {
$(this).closest("form").find("input[type=text], textarea").val("");
}
function main() {
$("form").on("click", "#cliccami", clearAll);
}
main();
function clearAll() {
$(this).closest("form").find("input[type=text], textarea").val("");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form>
<div>
<label>First Name:</label>
<input type="text" id="first-name">
</div>
<div>
<label>Last Name:</label>
<input type="text" id="last-name">
</div>
<div>
<label>Comments:</label>
<textarea id="comments"></textarea>
</div>
<input type="button" name="button" value="Click" id="cliccami">
</form>
Use jQuery's .val() function to set the value of a input element. Check the snippet for an example:
function clearAll() {
$(":input[type=text]").val("");
}
function main() {
$("#cliccami").on("click", clearAll);
}
main();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="test">
<input type="button" name="button" value="Click" id="cliccami">
You can bind your function using the onclick attribute. And use reset method to reset the entire form this way.
function main(){
// reset form
$('#my-form')[0].reset();
// do whatever you want
alert('Form cleared!');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<div class="container">
<h2>Form</h2>
<form id="my-form">
<div class="form-group">
<label for="first-name">First Name:</label>
<input type="text" class="form-control" id="first-name">
</div>
<div class="form-group">
<label for="last-name">Last Name:</label>
<input type="text" class="form-control" id="last-name">
</div>
<div class="form-group">
<label for="comments">Comments:</label>
<textarea class="form-control" id="comments"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" onclick="main()" class="btn btn-default">Clear All</button>
</form>
</div>
Try this
<form id="form1" action="">
<input type="text">
<input type="text">
<textarea name="" id="" cols="30" rows="10"></textarea>
<input type="button" name="button" value="Click" id="cliccami">
</form>
function clearAll() {
$('#form1 input, #form1 textarea, #form1 select').each(function() {
$(this).val('');
});
}
$("#cliccami").on('click',function(){
clearAll();
});
$('#clearit').click(function(){
$(":input[type=text]").val("");
setTimeout(function(){ afteremptyfield(); }, 1000);
})
function afteremptyfield(){
alert("Function trigged after clearing fields")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="test">
<input type="button" name="button" value="Clear and trigger a function" id="clearit">
This is how it could be done....

How to make a button clickable only if the textfield is entered

I had a textfield to enter the emailId..Iam getting that value stored in $rootScope.emailId.
Now when I click the submit button,I must take to next page only if the emailId is entered or else it must give an alert saying that must be filled.
Currently it is in form and i am using required="true" and form.$valid but still its not working is there any other way to achieve this.
<form name="customerForm" class="form-horizontal">
<div class="form-group">
<label for="inputEmail" class="col-lg-4 col-lg-offset-1 control-label">Email address</label>
<div class="col-lg-4">
<input class="form-control" ng-model="$root.customerDetails.eMail" placeholder="Enter customer email" type="email" required focus value="{{emailId}}">
</div>
</div>
</form>
--
<div class="col-lg-1">
<button type="submit" class="btn btn-primary right-button" ng-click="$ctrl.proceedToPaymentDetails()" ng-disabled="$ctrl.customerDetails">Next</button>
</div>
Currently the form and the button are not in the same html page..Is der any way to fix this.
change ng-disabled="customerForm.$invalid" or you can also check the value of email id inside your proceedToPaymentDetails() method for alert message.
Please gone throw this example code for your better understanding
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form novalidate>
First Name:<br>
<input type="text" ng-model="user.firstName"><br>
Last Name:<br>
<input type="text" ng-model="user.lastName">
<br><br>
Email:<br>
<input type="text" ng-model="user.emailID">
<br><br>
<button ng-click="proceedToPaymentDetails()">Next</button>
</form>
<p>form = {{user}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.user = {firstName:"", lastName:"",emailID:""};
$scope.proceedToPaymentDetails = function() {
alert($scope.user.emailID);
};
});
</script>
</body>
</html>

How to submit for after all the fields are filled in JavaScript

Basically I have a HTML form that contains a textbox and a submit button, what I want is when I pressed submit button it should check for the textbox that it have no error then proceed with submission.
Here is my button code:
<form id="thisform">
<div id="Registeration" class="Registeration">
<input type="text" id="textbox" class="textbox"
placeholder="My textbox" name="fBox" maxlength="30"/>
</div>
<div class="Registration_Submit_Div">
<input type="submit" value="submitform" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn" onclick="submit()"/>
</div></form>
function(){
alert('hello');
return false;
}
Here's a plain JS example where the form is only submitted if the text is at least 5 characters long.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="POST" action="result.html" class="da-form">
<input type="text" name="textbox" class="textbox">
<input type="submit" class="submit">
</form>
<script>
var formEl = document.querySelector('.da-form');
var submitBtn = document.querySelector('.da-form .submit');
var textEl = document.querySelector('.textbox');
submitBtn.addEventListener('click', function(event) {
event.preventDefault();
if (textEl.value.length >= 5) {
formEl.submit();
} else {
console.error('text should be at least 5 chars long');
}
console.log();
});
</script>
</body>
</html>
you can use AngularJS:
Angular allow you to get status about your form: $invalid/$valid
the following code will disable the button until the form will be valid:
<input type="button" value="Submit" ng-click="submit()" class="button" ng-disabled="myForm.$invalid">
please see the following example:
HTML:
<div ng-app>
<form ng-controller="FormController" name="myForm">
<div class="header padding-b--10">Form Area</div>
<div class="padding-b--10">
<input name="empId" placeholder="Employee ID" ng-model="data.empId"
style="padding:5px" required/>
<span ng-if="myForm.empId.$dirty && myForm.empId.$invalid" ng-bind="invalid" class="error"></span>
</div>
<div class="padding-b--10">
<input name="empEmail" type="email" placeholder="Email" ng-model="data.empEmail"
style="padding:5px" required/>
<span ng-if="myForm.empEmail.$dirty && myForm.empEmail.$invalid" ng-bind="invalid" class="error"></span>
</div>
<input type="button" value="Submit" ng-click="submit()" class="button" ng-disabled="myForm.$invalid">
</form>
Controller:
function FormController($scope){
$scope.invalid = "Invalid";
$scope.submit = function(){
console.log($scope.data);
}
};
Working Example: https://jsfiddle.net/pqz3hsac/22/

ngSubmit is not triggering function in controller

I am relatively very new to AngularJS and javascript Please be merciful while answering.
I am trying to create one sample application where I want to nest controllers. MainController which will always be there acting as parent container which will render menu and user name on top if user is logged in. For now I am checking if user is stored in localStorage.
Each page will have its own controller which will do page specific things.
I am stuck at ng-submit and why its not working?
Any help is appreciated.
Index.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-resource.js"></script>
<script src="angularapp.js"></script>
</head>
<body ng-app="myAngularApp">
<div ng-controller="MainController">
<div ng-show="isLoggedIn">Menu</div>
<div ng-view>
</div>
</div>
</body>
login.html
<from ng-submit="login()">
<input type="text" id="username" ng-model="username"></input>
<input type="password" id="password" ng-model="password"></input>
<input type="submit" value="submit" id="submit" ng-submit="login()"></input>
</form>
angularapp.js
angular.module('myAngularApp',['ngRoute','ngResource'])
.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/home',{
controller:'SubController',
templateUrl:'templates/home.html'
})
.when('/login',{
controller:'MainController',
templateUrl:'templates/login.html'
});
}])
.controller('MainController',['$scope','$window','userService',function($scope,$window,userService){
$scope.isLoggendIn=userService.isLoggedIn;
console.log('here I come');
$scope.username='';
$scope.password='';
$scope.login=function(){
alert('Ignored???');
$window.localStorage['myUser']={username:$scope.username,password:$scope.password};
consoel.log('user is logged in now');
};
}])
.controller('SubController',['$scope',function($scope){
$scope.myContent='Contenst to show after logged in';
}])
.service('userService',['$window',function($window){
var self=this;
self.isLoggedIn=function(){
if($window.localStorage['myUser'])
return true;
else
return false;
};
}]);
Please change your code. Seems you have made spelling mistake.
<from ng-submit="submit()">
to:
<form ng-submit="submit()">
Also replace the following code.
<input type="submit" value="submit" id="submit" ng-click="submit()"></input>
No need of ng-submit="login()" in this place type="submit is enought and last one is button not input
<from ng-submit="submit()">
<input type="text" id="username" ng-model="username"></input>
<input type="password" id="password" ng-model="password"></input>
<button type="submit" value="submit" id="submit"></button>
</form>
Edit your code:
<input type="submit" value="submit" id="submit" ng-submit="login()"></input>
Must be as below:
<input type="submit" value="submit" id="submit" ng-click="submit()"></input>
I think there is a problem in your login.html. remove login() because you have submit()
<from ng-submit="submit()">
<input type="text" id="username" ng-model="username"></input>
<input type="password" id="password" ng-model="password"></input>
<input type="submit" value="submit" id="submit"></input>
</form>

Can I change button text as input text value changed?

I have this very simple form:
<div ng-app>
<div ng-controller="Ctrl">
<form>
<input type="text" value="" onchange="angular.element(this).scope().change(this)" />
<br />
<input type="submit" name="button1" value="{{text}}" />
</form>
</div>
</div>
And this JS:
function Ctrl($scope) {
$scope.text = "New";
$scope.change = function (element) {
$scope.text = element.value;
$scope.$apply();
}
}
jsfiddle
Currently, the button value is updated when I leave the text field. How can I change the button value as user is typing?
There is no need to reinvent the wheel, just use ng-model directive:
<input type="text" ng-model="text" />
DEMO: http://jsfiddle.net/d28L8bc9/1/
HTML:
<div ng-app>
<div ng-controller="Ctrl">
<form>
<input type="text" value="" ng-model="text" />
<br />
<input type="submit" name="button1" value="{{text}}" />
</form>
</div>
</div>
JS:
function Ctrl($scope) {
$scope.text = "New";
}

Categories