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

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>

Related

redirect event with javascript

I'm doing a project and I don't understand the front end well.
I have this html page:
<form class="form-group" action="/create" method="post" enctype="multipart/form-data">
<div class="title">
<h1>Cadastre seu produto</h1>
</div>
<div class="single-input">
<input class="form-control" placeholder="nome do produto" type="text" id="nome_produto" name="nome_produto">
</div>
<div class="single-input">
<input class="form-control" placeholder="quantidade em estoque" type="number" id="quantidade" name="quantidade">
</div>
<div class="single-input">
<input class="form-control" placeholder="preco do produto" type="number" id="preco_produto" name="preco_produto">
</div>
<button onclick="loadPage()" id="button" type="submit" class="btn btn btn-danger">ENVIAR</button>
</form>
I want that when I click on the SUBMIT button, I am redirected to another page, I want to do this using Javascript.
I tried to do this:
<script type="text/javascript">
function loadPage(){
window.location("http://localhost:8080/list")
}
but it's not working, every time I click on the button I'm redirected to a blank page
Any solution ?
Window.location is a property not a function. So it should be
window.location = "http://localhost:8080/list";
More details here: https://developer.mozilla.org/en-US/docs/Web/API/Window/location

Bootstrap JavaScript for disabling form submissions if there are invalid fields & the rest form is not working as intended

I am using the bootstrap version 4. Index.php includes the below contact form. I want users to see the validation messages when they click submit to draw their attention to the required fields they have missed. For example, when a user hits submit without filling any field, the user sees the below, which is the behavior I want to achieve, and I currently have:
[please note that to save space in this post, all images can be shown by clicking on run code snippet]
<img src="https://i.stack.imgur.com/h1KwJ.png" width="50%" height="50%" />
The contact form: Index.php
<!DOCTYPE HTML>
<html>
<head>
<title>Contact form</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div class ="container">
<div class="col-lg-6 push-lg-3">
<h1> Contact us</h1>
<p>Fill out the below form to contact us</p>
<form id="contactForm" class="contact-form needs-validation" action="form.php" method="POST" novalidate>
<div class="contact-form-success alert alert-success d-none mt-4" id="contactSuccess">
<strong>Success!</strong> Your message has been sent to us.
</div>
<div class="contact-form-error alert alert-danger d-none mt-4" id="contactError">
<strong>Error!</strong> There was an error sending your message.
<span class="mail-error-message text-1 d-block" id="mailErrorMessage"></span>
</div>
<div class="form-row">
<div class="form-group col-lg-6">
<label for="name" class="required font-weight-bold text-dark">Full Name</label>
<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>
</div>
<div class="form-group col-lg-6">
<label class="required font-weight-bold text-dark">Email Address</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<label class="font-weight-bold text-dark">Phone</label>
<input type="text" value="" data-msg-required="Please enter the phone number." maxlength="100" class="form-control" name="phone" id="phone" required>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<label class="required font-weight-bold text-dark">Message</label>
<textarea maxlength="5000" data-msg-required="Please enter your message." rows="5" class="form-control" name="message" id="message" required></textarea>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<div class="g-recaptcha" data-sitekey="Your_Public_Key"></div>
</div>
</div>
<div class="form-row">
<div class="form-group col">
<input type="submit" value="Send Message" class="btn btn-primary btn-modern" data-loading-text="Loading...">
</div>
</div>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/view.contact.js"></script>
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
else {
$("#submit-btn .text").text("Enviado");
$("#submit-btn").addClass("active");
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
<script>
$("#contactForm").validate();
</script>
</body>
</html>
The issue
I have the issue that when the user hits submits, everything goes as planned, and the form refreshes, and the success message appears, but the form refreshes with validation showing red boxes, which is the problem I want to solve. This is how a successful form submission currently looks like and this is incorrect:
<img src="https://i.stack.imgur.com/eV7A6.png" width="50%" height="50%" />
When the user hits submit, I want the user to see the success message; I want the form to refresh without green or red boxes to the input fields. To better understand this, please have a look at the below behavior I want to achieve:
<img src="https://i.stack.imgur.com/0Yf01.png" width="50%" height="50%" />
I know that the issue is in the JavaScript for disabling form submissions (above) or in the view.contact.js:
I appreciate any insights or guidance about how I can fix this.
One more question I have is this: Will I need the below code?
<script>
$("#contactForm").validate();
</script>
Any comment on how to make this code better is highly appreciated.
From the official documentacion:
To reset the appearance of the form (for instance, in the case of
dynamic form submissions using AJAX), remove the .was-validated class
from the again after submission.
Bootstrap > Form > Validation > How it Works
In your case, you need to add the following line:
$form.removeClass('was-validated');
Inside:
$.ajax({...})
.done(function() {
//HERE
),
.always({...});

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/

AngularJS Form validation Group error message

In angularJs FORM SUBMIT how to display all validation messagees in one single div at bottom of the page. Ex:
<div id="err-msg"> <!-- error message will come here --></div>
I referred documents but all are displaying below the text box using
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="alert alert-danger">Enter a valid email.</p>
How to write one area to bind all the messages in to same place (avoid use this userForm.email.$invalid)
Note I tried ng-message but am not clear any one help me. Please refer the below code for normal HMTL jQuery error display like need to take care using the AngularJS
HTML
<div id="main">
<form> <div><input id="email_txt" type="text" name ="email" value="" > </div>
<div><input id="pass_txt" type="password" name ="password" value="" > </div>
<div><input id="validate_btn" type="submit" value="Validate" > </div>
</form>
</div>
<div id="err-msg"> <!-- error message will come here --></div>
jQuery:
$('#main').on('click', '#validate_btn', function() {
if($('#email_txt').val().length == 0){
$('#err-msg').val("Please enter emailid!");
}else if($('#pass_txt').val().length == 0){
$('#err-msg').val("Please enter password!");
}
...
...
else{
alert("Good");
}
});
AngularJS current code :
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8">
<p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p>
<p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p> </div>
<input type="email" name="email" class="form-control" ng-model="email">
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
<button type="submit" class="btn btn-primary">Submit</button>
<form>
app.js
.controller('validatectrl',['$scope',function($scope){
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
alert('Good');
}
};
}]);
How to rewrite?
If a form is invalid, the errors will be stored in the object $scope.form.$error. Please check console of this JSFiddle. From the $error property on the form, you can populate the error messages.
angular.module('Joy', [])
.controller('FormCtrl', ['$scope', function ($scope) {
$scope.user = {};
$scope.submit = function () {
console.log($scope.userInfo);
};
}]);
The HTML:
<div ng-app="Joy" id="play-ground">
<form name="userInfo" novalidate ng-controller="FormCtrl">
<div class="ui input">
<input ng-model="user.email" ng-message="YOU ARE WRONG" name="User Email" type="email">
</div>
<div class="ui input">
<input ng-model="user.name" name="User Name" type="text" required>
</div>
<div class="ui divider"></div>
<button class="ui primary button" ng-click="submit()">Submit</button>
<div class="ui positive message">User: {{ user | json }}</div>
</form>
</div>

How to perform client-side form-validation on password

I am doing a simple sign-up page. For the password stuff, I need to check the new password and confirmed password are the same but no idea how
<div class="row">
<!--New Username-->
<div class="large-4 columns form-text">New Username</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="text" class="form-input" name="username" required>
</div>
</div>
<br/>
<div class="row">
<!--New email-->
<div class="large-4 columns form-text">Email</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="email" class="form-input" name="email" pattern="[a-zA-Z]*#[a-zA-Z]*" required>
</div>
</div>
<br/>
<div class="row">
<!--New Passwrord-->
<div class="large-4 columns form-text">New Password</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="password" class="form-input" name="password" required>
</div>
</div>
<br/>
<div class="row">
<!--Reconfirm new password-->
<div class="large-4 columns form-text">Re-enter Password</div>
<div class="large-8 columns">
<div class="input-icon font-awesome"></div><input type="password" class="form-input" name="password-confirm" required>
</div>
</div>
That's quite a bit of code, but I broke out an example on a fiddle.
Simplified HTML:
<form id="passwordForm" action="#" method="POST">
Password:<br>
<input type="password" id="password"><br>
Confirm Password:<br>
<input type="password" id="confirmPassword"><br>
<input type="submit" id="submitButton" value="Check 'Em">
</form>
<div id="responseDiv"></div>
I used jQuery:
$(document).ready(function () {
$("#submitButton").click(function (e) {
e.preventDefault();
var matched,
password = $("#password").val(),
confirm = $("#confirmPassword").val();
matched = (password == confirm) ? true : false;
if(matched) {
//Submit line commented out for example. In production, remove the //
//$("#passwordForm").submit();
//Shows success message and prevents submission. In production, comment out the next 2 lines.
$("#responseDiv").html("Passwords Match");
return false;
}
else {
$("#responseDiv").html("Passwords don't match...");
return false;
}
});
});
Many times new learners will forget the e.preventDefault(); Without it, the form will submit regardless of any validation. Return false if there is something wrong, and the form will not submit.
There is an event listener on the submit button. If it is clicked, or the enter key is pressed will focused in the form, it will run the validation. If everything is fine, it will post the information to the URL in the action attribute of the form tag.
Another important point is to always re-validate on the server side. If a user has their Javascript turned off the form will post the information regardless of what is in your validation script.
with normal javascript, just adapt to your source code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function pass() {
var pass_1 = document.forms["myForm"].pass_1.value.length;
var pass_2 = document.forms["myForm"].pass_2.value.length;
if (pass_1 != pass_2) {
alert("the pass and repeat pass must be equal");
return false;
}
return true;
}
</script>
</head>
<body>
<form method="post" action="" name="myForm" onSubmit="pass(); return false;">
<input type="password" placeholder="type your pass" name="pass_1">
<input type="password" placeholder="confirm your pass" name="pass_2">
<input type="submit" value="validate">
</form>
</body>
</html>
the same code above but with the redirect: http://jsfiddle.net/m7BrM/
option 2 use a plugin:
http://www.technicalkeeda.com/jquery/password-and-confirm-password-validation-in-jquery

Categories