How to use unbind show method in jQuery? - javascript

I am trying password mismatch error to be displayed when user put two different passwords in input fields on user registration form, but in my program it displays error message already in input field. In my program, the unbind() method is not working.
HTML:
<form action="adduser.php" method="POST" id="registerCandidates" enctype="multipart/form-data">
<div class="form-group">
<input class="form-control input-lg" type="password" id="password" name="password" placeholder="Password *" required>
</div>
<div class="form-group">
<input class="form-control input-lg" type="password" id="cpassword" name="cpassword" placeholder="Confirm Password *" required>
</div>
<div id="passwordError" class="btn btn-flat btn-danger hide-me" >
Password Mismatch!!
</div>
<div class="form-group">
<button type="submit" class="btn btn-flat btn-success" name="register">Register</button>
</div>
</form>
Jquery:
<script type="text/javascript">
$(document).ready(function(){
$("#registerCandidates").bind("submit", function(e) {
e.preventDefault();
if( $('#password').val() != $('#cpassword').val() )
{
$('#passwordError').show();
}
else
{
$(this).unbind('submit').submit();
}
});
});
</script>
Image (it is my user registration form image):

You don't need to unbind. Just avoid calling e.preventDefault() when you want to allow the form to submit. So put that call in the if branch where validation fails.
$("#registerCandidates").bind("submit", function(e) {
if( $('#password').val() != $('#cpassword').val() )
{
$('#passwordError').show();
e.preventDefault();
}
});
When the user edits the password fields after a failing submit, you should hide the error message.
$("#password, #cpassword").on("input", function() {
$("#passwordError").hide();
});
Here is full working code
$("#registerCandidates").bind("submit", function(e) {
if ($('#password').val() != $('#cpassword').val()) {
$('#passwordError').show();
e.preventDefault();
}
});
$("#password, #cpassword").on("input", function() {
$("#passwordError").hide();
});
.hide-me {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="adduser.php" method="POST" id="registerCandidates" enctype="multipart/form-data">
<div class="form-group">
<input class="form-control input-lg" type="password" id="password" name="password" placeholder="Password *" required>
</div>
<div class="form-group">
<input class="form-control input-lg" type="password" id="cpassword" name="cpassword" placeholder="Confirm Password *" required>
</div>
<div id="passwordError" class="btn btn-flat btn-danger hide-me">
Password Mismatch!!
</div>
<div class="form-group">
<button type="submit" class="btn btn-flat btn-success" name="register">Register</button>
</div>
</form>

Related

Why is my form not returning an alert when password does not match the confirm password field Javascript?

So I'm new to JS, and I'm trying to make this form prevent submission if password does not match the confirm password field. However, when I enter in 2 different passwords, I don't get an alert like I've coded in the script below. Any thoughts? For reference, the form was built w/ bootstrap.
<form class="form-signin">
<div class="form-label-group">
<input type="text" id="fullName" class="form-control" placeholder="Username" required autofocus>
<label for="fullName">Full name</label>
</div>
<div class="form-label-group">
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required>
<label for="inputEmail">Work email</label>
</div>
<div class="form-label-group">
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<label for="inputPassword">Password</label>
</div>
<div class="form-label-group">
<input type="password" id="inputConfirmPassword" class="form-control" placeholder="Password" required>
<label for="inputConfirmPassword">Confirm password</label>
</div>
<button class="btn btn-lg btn-primary btn-block text-uppercase" id ="register-btn" type="submit">Register</button>
<hr class="my-4">
<div class="registration-login">
<p class="already-have__account">Already have an account?</p> Login
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="registration__section">
<h2>Innovative supply chain teams use Rumi to manage scalable and sustainable packaging.
</h2>
</div>
<script>
var form = document.getElementById('form-signin');
form.onsubmit = function() {
if (inputPassword.value !== inputConfirmPassword.value) {
alert("Your passwords don't match");
return false;
}
else {
return true;
}
}
Just a minor mistake.
You are using get getElementById.
var form = document.getElementById('form-signin');
There is no id with 'form-signin',
<form class="form-signin">
Rename the class to id.
<form id="form-signin">
Check out this (JSFiddle). It's working here.

How to move cursor-to-next from one input to another input and button by pressing keyboard enter in angular 6

From the Login design page I have to move the cursor from the Username to the Password <input>, and the same procedure from Password to the <button> click event so that I can login to my page by pressing the keyboard enter key, in Angular 6.
My HTML code below:
<div class="ibox-content login-form">
<div class="form-group">
<input type="text" class="form-control" id="inputUername" placeholder="Username" [(ngModel)]="loginData.username" autofocus >
</div>
<div class="form-group">
<input type="password" class="form-control" id="inputPassword" placeholder="Password" [(ngModel)]="loginData.password" >
</div>
<button type="submit" icon="fa fa-sign-in" class="btn btn-primary" [disabled]="loginData.username == '' || loginData.password == ''"
(click)="login()">Login</button>
<div class="login-error-message" *ngIf="content.loginFailed">
<p>Invalid username or password</p>
</div>
</div>
Use (keyup.enter) = "focusablePassword.focus()" to input Username and call #focusablePassword to input Password, this would perform the task and same for button as shown in code below.
<div class="ibox-content login-form">
<div class="form-group">
<input type="text" class="form-control" id="inputUername" placeholder="Username" [(ngModel)]="loginData.username" autofocus (keyup.enter)="focusablePassword.focus()">
</div>
<div class="form-group">
<input #focusablePassword type="password" class="form-control" id="inputPassword" placeholder="Password" [(ngModel)]="loginData.password" (keyup.enter)="focusableSubmit.focus()" >
</div>
<button #focusableSubmit type="submit" icon="fa fa-sign-in" class="btn btn-primary" [disabled]="loginData.username == '' || loginData.password == ''"
(click)="login()">Login</button>
<div class="login-error-message" *ngIf="content.loginFailed">
<p>Invalid username or password</p>
</div>
</div>

Timeout function works for one form but ignores the other

I'm having a very specific problem. I have two forms on a page, bootstrap validator included and it works just fine, except that it doesn't have the RegEx check for email input. So I created a short RegEx validation, but when I try to handle error messages, they work as intended only for the second form. When I click submit button, error messages show up on both form, but timeout functions works nly for the latter one. Submit button for the top form keep creating new error messages whenever I click on it. Any advice? Please see my code below:
HTML:
Top form:
<form action="" method="POST">
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Full Name:" required>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email Address:" required>
</div>
<div class="form-group">
<input type="tel" class="form-control" name="phone" placeholder="Phone Number:" required>
</div>
<div class="form-group">
<input type="text" class="form-control" name="amount" placeholder="Investment Amount (£)">
</div>
<button class="btn btn-block btn-submit" type="submit" name="submit">Enquire Now</button>
Bottom form:
<form action="" method="POST" class="row form-find-more">
<div class="form-group col-lg-3 col-md-3">
<input type="text" name="name" placeholder="Full Name*:" required>
</div>
<div class="form-group col-lg-3 col-md-3">
<input type="email" name="email" placeholder="Email Address*:" required>
</div>
<div class="form-group col-lg-3 col-md-3">
<input type="text" name="phone" placeholder="Phone Number*:">
</div>
<div class="form-group col-lg-3 col-md-3">
<button class="btn" type="submit" name="submit">Submit Request</button>
</div>
</form>
My jQuery snippet:
<script>
var emailReg = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|
(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var elm = $('<div class="help-block with-errors">Please enter a valid e-
mail</div>');
$(document).on('click', 'form button[type=submit]', function(e) {
var isValid = emailReg.test(jQuery.trim($(e.target).parents('form').find("input[type=email]").val()));
if(!isValid) {
e.preventDefault(); //prevent the default action
$('form').append(elm);
}
});
setTimeout(function() {
elm.detach();
}, 5000);
</script>
Managed to fix the problem by some code edits:
var emailReg = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|
(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-
9]+\.)+[a-zA-Z]{2,}))$/;
var elm = $('<div class="help-block with-errors">Please enter a valid e-mail</div>');
$(document).on('click', 'form button[type=submit]', function(e) {
var isValid = emailReg.test(jQuery.trim($(e.target).parents('form').find("input[type=email]").val()));
if(!isValid) {
e.preventDefault(); //prevent the default action
$('form').append(elm.prop('outerHTML'));
setTimeout(function() {
$('.help-block.with-errors').remove();
}, 3000);
}
});
Thank you everyone who helped.

How to retain the values in form after validation error in angularjs

I have a validation in my form for email. If the user is already registered, it shows the alert and resets the form with null value. I need the alert message as well as data should retain in the form.
Thanks in advance.
https://plnkr.co/edit/WhdRmJmLs69yaf6Q2uYI?p=preview
<div class="form-group">
<label class="control-label col-sm-2" for="firstName">First Name:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="firstName" ng-disabled="!edit" name="firstName" ng-model="user.firstName" ng-required="true">
<span style="color:red" ng-show="userForm.myName.$touched && userForm.myName.$invalid">Please enter a First Name</span>
</div>
<label class="control-label col-sm-2">Email:</label>
<div class="col-xs-4"><input type="email" id="email" class="form-control" ng-disabled="!edit" name="email" ng-model="user.email" ng-required="true">
<span style="color:red" ng-show="userForm.email.$touched && userForm.email.$invalid">Please enter valid email ID</span>
</div>
</div>
<div class="panel-footer">
<button type="button" ng-click='edit=!edit'id="Edit" ng-show="!edit" class="btn btn-default" >Edit</button>
<button ng-show="edit" id="save" type="submit" ng-click='addOrModifyUser(user)' class="btn btn-default"
ng-disabled="userForm.$invalid">Save
</button>
<a ng-if="user.accountId" ui-sref="account.locations.contacts({accountId: user.accountId})">
<button type="type" class="btn btn-default">Cancel</button>
</a>
</div>
I?p=preview
Don't know exactly what your problem is here but this is how I would have solved a custom email validation check in angular 1.x.
Html:
<form ng-submit="submit()">
<input type="email" class="form-control" id="email" name="email" placeholder="email" ng-model="formModel.email" />
<span ng-show="formModel.$submitted && formModel.teamName.$error.exists">Email already exists</span>
</form>
Js: (in your angular controller) where "EmailService" would be your http service of choice that checks if email exists against your backend:
myApp.controller('mainController', function($scope, EmailService) {
$scope.submit = function() {
$scope.formModel.email.$setValidity("exists", true);
EmailService.emailExist($scope.formModel.email, { // check if email exists
success: function(exists) {
$scope.$apply(function(){
$scope.formModel.email.$setValidity("exists", !exists); // set validation flag
});
if($scope.formModel.$valid) {
// submit if valid
}
}
}
}
}
Good luck!

JQuery code I wrote stopped working, is there anywrong I've overlooked?

For the below code I want the content of the submit button with the .btn-primary attribute to change to "Success!" only if the input fields are all not null.
At preset the code goes straight to success when the button is press whether or not the fields have content.
I thought it might be because the fields may somehow already have a value that is not null so I ran this code: alert($('#Comment').attr("value")); and it returned undefined in the alert message. Undefined is the same as null in js/jquery isn't it?
I got this code to work earlier and it was typed almost the same way with just a few changes. I undid the changes but it still does not work.
Any help will be appreciated. (If anyone knows this) Are there instances in which the same code could not work at a different time, all things being equal?
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
$(document).ready(function () {
var Fname = $('#FirstName').attr("value");
var Lname = $('#LastName').attr("value");
var Email = $('#Email').attr("value");
var Comment = $('#Comment').attr("value");
$(".btn-primary").click(function () //This block should say, if all fields are not null changed the content of button to "Success!" and change the content of <h1> to "THANKS, I'VE GOT YOUR MESSAGE."
{
if (Fname != null && Lname != null && Email != null && Comment != null)
{
$("button").html("Success!");
$("h1").html("THANKS, I'VE GOT YOUR MESSAGE");
}
})
});
</script>
And this is the html on the same page
<form class="form-horizontal" role="form" action="/Home/Contact" method="post">
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" data-val="true" data-val-required="Please enter your first name" id="FirstName" type="text" placeholder="First Name" name="FirstName"/>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your last name" id="LastName" type="text" placeholder="Last Name" name="LastName"/>
<span class="field-validation-valid text-danger" data-valmsg-for="LastName" data-valmsg-replace="true" data-></span>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your email" id="Email" name="Email" type="email" placeholder="Email#Address.com"/>
<span class="field-validation-valid text-danger" data-valmsg-for="Email" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" required data-val="true" data-val-required="Please enter a brief detailed message" id="Comment" name="Comment" placeholder="A Short but detailed message"></textarea>
<span class="field-validation-valid text-danger" data-valmsg-for="Comment" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<button type="submit" class="btn btn-primary btn-sm active" value="submit">Submit</button>
<input type="reset" class="btn btn-default btn-sm active" value="reset">
</div>
</div>
</form>
When your document loads you are storing the value of Fname, Lname ..... so on. The issue is you then use these values in your conditional test but the values will not have changed as they are just the raw value from the first time the page loaded. One quick fix would be to bring these inside the click so on every click they can re evaluated
Also when checking you are only checking for null but these are not going to equal null anyway. Better would be to fully validate them or just test for generic truthy which excludes the falsy values such as null, undefined, empty string
$(document).ready(function () {
$(".btn-primary").click(function (e)
{
var Fname = $('#FirstName').val();
var Lname = $('#LastName').val();
var Email = $('#Email').val();
var Comment = $('#Comment').val();
//ADDED JUST TO STOP THE FORM SUBMITTING
e.preventDefault();
//very quick test but this could be a lot more detailed for true validation on each field
if (Fname && Lname && Email && Comment) {
$("button").html("Success!");
$("h1").html("THANKS, I'VE GOT YOUR MESSAGE");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>
<form class="form-horizontal" role="form" action="#" method="post">
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" data-val="true" data-val-required="Please enter your first name" id="FirstName" type="text" placeholder="First Name" name="FirstName" />
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your last name" id="LastName" type="text" placeholder="Last Name" name="LastName" /> <span class="field-validation-valid text-danger" data-valmsg-for="LastName" data-valmsg-replace="true" data-></span>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your email" id="Email" name="Email" type="email" placeholder="Email#Address.com" /> <span class="field-validation-valid text-danger" data-valmsg-for="Email" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" required data-val="true" data-val-required="Please enter a brief detailed message" id="Comment" name="Comment" placeholder="A Short but detailed message"></textarea> <span class="field-validation-valid text-danger" data-valmsg-for="Comment" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<button type="submit" class="btn btn-primary btn-sm active" value="submit">Submit</button>
<input type="reset" class="btn btn-default btn-sm active" value="reset">
</div>
</div>
</form>

Categories

Resources