enabled button if password match - javascript

here is my script
$("#reg_confirm_pass").blur(function(){
var user_pass= $("#reg_pass").val();
var user_pass2=$("#reg_confirm_pass").val();
var enter = $("#enter").val();
if(user_pass.length == 0){
alert("please fill password first");
enter.disabled = true;
} else if (user_pass == user_pass2 ){
enter.disabled = false;
} else {
enter.disabled = true;
alert("Your password doesn't same");
}
});
this my html
Password : <input type="password" name="user[user_pass]" id="reg_pass" required="required">
Confirm password <input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
i am really new in Javascript and jQuery, and this is my first using jquery. i need to make a disabled button if the password doesn't match but, after i put the same password the button is still disabled.

$("#reg_confirm_pass").blur(function() {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
//var enter = $("#enter").val();
if (user_pass.length == 0) {
alert("please fill password first");
$("#enter").prop('disabled',true)//use prop()
} else if (user_pass == user_pass2) {
$("#enter").prop('disabled',false)//use prop()
} else {
$("#enter").prop('disabled',true)//use prop()
alert("Your password doesn't same");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Password :
<input type="password" name="user[user_pass]" id="reg_pass" required="required">Confirm password
<input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>
Use .prop()

You need to set disable attribute like this in jquery $("#enter").attr('disabled',true);
if(user_pass.length == 0){
alert("please fill password first");
$("#enter").attr('disabled',true);
} else if (user_pass == user_pass2 ){
$("#enter").attr('disabled',false);
} else {
$("#enter").attr('disabled',true);
alert("Your password doesn't same");
}

The .prop( propertyName, value ) allow you set one or more properties for the set of matched elements.
JS
$(function() {
$("#reg_confirm_pass").blur(function() {
var user_pass = $("#reg_pass").val();
var confirm_user_pass = $("#reg_confirm_pass").val();
var enter = $("#enter");
if (user_pass.length == 0) {
alert("please fill password first");
enter.prop('disabled', true)
}
else if (user_pass == confirm_user_pass) {
enter.prop('disabled', false)
}
else {
enter.prop('disabled', true)
alert("Your password doesn't match");
}
});
});
HTML
Password: <input type="password" name="user[user_pass]" id="reg_pass" required="required">
Confirm password: <input type="password" name="user[user_confirm_pass]" id="reg_confirm_pass" required="required">
<button type="submit" id="enter" disabled="true" value="Register">Register</button>

I believe the other answers are right on target. I set up a simple 'jsfiddle' using jquery and its .prop() method to better illustrate here.
NOTE: I would probably bind to another event to make it fire when changes are made to either input element.
$("#reg_confirm_pass").blur(function(){
var user_pass= $("#reg_pass").val();
var user_pass2=$("#reg_confirm_pass").val();
var enter = $("#enter").val();
if(user_pass.length == 0){
alert("please fill password first");
$("#enter").prop('disabled',true);
} else if (user_pass == user_pass2 ){
$("#enter").prop('disabled',false);
} else {
$("#enter").prop('disabled',true);
alert("Your password doesn't same");
}
});

Actually blur will not enable the button instantly, keyup eventhandler does the best job. Here's the below code.
$("#reg_pass").keyup(function () {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
if (user_pass == user_pass2) {
$("#enter").prop('disabled', false)//use prop()
} else {
$("#enter").prop('disabled', true)//use prop()
}
});
$("#reg_confirm_pass").keyup(function () {
var user_pass = $("#reg_pass").val();
var user_pass2 = $("#reg_confirm_pass").val();
if (user_pass == user_pass2) {
$("#enter").prop('disabled', false)//use prop()
} else {
$("#enter").prop('disabled', true)//use prop()
}
});
Here it responds to the changes in either of the text boxes instantly.
Check it here.
Any better solution than this, please let me know. Thank you.

Related

Unable to stop form from submitting with empty inputs

I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}

How to get `form.field.value` in jQuery?

in javascript i can validate a form on submit like below:-
<form action="" method="post" onsubmit="return validate(this)">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
function validate(loginForm){
if(loginForm.uName.value == ''){
alert('Please Enter Username');
loginForm.uName.focus();
}else if(loginForm.passKey.value == ''){
alert('Please Enter Password');
loginForm.passKey.focus();
}else {
return true;
}
}
</script>
I tried with below jQuery Code
<form action="" method="post">
<input type="text" name="uName" id="uName" />
<input type="password" name="passKey" id="passKey" />
<input type="submit" name="loginBtn" value="login" />
</form>
<script type="text/javascript">
$('form').submit(function(loginForm){
if(loginForm.uName.val() == ''){
alert('Please enter username');
loginForm.uName.focus();
}else if(loginForm.passKey.val() == ''){
alert('Please enter username');
loginForm.passKey.focus();
}else {
return true;
}
return false;
});
</script>
But not works me... please help me...!
like this?
$('#submit').click(function(){
if( $('#uName').val() == ''){
alert('empty');
}
});
http://jsfiddle.net/TTmYk/
the submit form has a typo in my fiddle u might need to fix that
See the Form Fields jQuery Plugin:
https://github.com/webarthur/jquery-fields
You can use the plugin as follows:
var form = $('form#id_form').fields();
form.name.val('Arthur');
form.age.hide();
form.description.css('height', 200);
Or this way:
var form = $('form#id_form').fieldValues();
form.name('Arthur');
form.age(29);
form.description('Web developer.');
var name = form.name();
The argument in the submit callback function is not the element instead it is the event. So inside the callback this represents the form element so you could just do this.uName.value and you can avoid the use of id as well.
So
$('form').submit(function(e){
if(this.uName.value == ''){
alert('Please enter username');
this.uName.focus();
}else if(this.passKey.value == ''){
alert('Please enter username');
this.passKey.focus();
}else {
return true;
}
return false;
});
Fiddle
Plus val() is jquery method, and in plain javascript you would use value and in this case that should be sufficient enough.
This will help you:
jQuery(function($) {
var $username = $('#uName'),
$password = $('#passKey');
$('form').submit(function() {
if ($username.val() == '') {
alert('Please enter username');
$username.focus();
} else if($password.val() == '') {
alert('Please enter username');
$password.focus();
} else {
return true;
}
return false;
});
});
Some points you need to keep in mind:
If you will work with the DOM you should wrap your code inside a jQuery(function() { ... }); block.
If you want to access a DOM element with jQuery you need to select it before using $(...).

Javascript alert on submit if text field is empty

So i want to alert the user if they submit the form with an empty text field
HTML:
<form id="orderform">
<input type="text" name="initials" id="initials" maxlength="3">
<p class="center">
<input type="image" src="#" id="submitbutton" name="submit" value="Place Order">
</p>
</form>
Javascript:
$('#orderform').submit(function() {
if($('#initials').length == 0){
alert('Please fill out your initials.');
}
});
Just make sure you return false in there somewhere-
$('#orderform').submit(function() {
if($('#initials').val() == ''){
alert('Please fill out your initials.');
return false;
}
});
$('#initials').length will check if the element exists. Try this:
$('#orderform').submit(function() {
if($('#initials').val().length == 0){
alert('Please fill out your initials.');
}
});
as lewsid pointed out, you should also return false if you want to cancel the submit
$('#orderform').submit(function(e) {
e.preventDefault();
if(!$.trim((this + ' input').val()).length){
alert('Please fill all the fields');
return false;
}
return true;
});
but is better if you do this with pure JS not jQuery
function funnjsTrim(input) {
return input
.replace(/^\s\s*/, '')
.replace(/\s\s*$/, '')
.replace(/([\s]+)/g, '-');
}
validate_form = function(form, mssg){
mssg = form_errors[mssg] || 'Error: empty field';
var form_to = form.name,
elems = document.forms[form_to].getElementsByTagName("input");
for(var i = 0; i < elems.length + 1; i++) {
if(elems[i].type != 'submit') {
var string = funnjsTrim(elems[i].value);
if(!string.length) {
alert(mssg);
error = 'error';
return false
}
}
}
if(typeof error == "undefined"){
alert('Valid');
return true;
}
}
so in your html
<form onsubmit="return validate_form(this)">
in this line: if(elems[i].type != 'submit') add || elems[i].class != 'your input class' to add exceptions
I'd use e.preventDefault() instead of return false. Return false also prevents events from bubbling and can have unintended consequences if you don't understand this. Also nest that preventDefault within your if, no reason to stop submission if things are good.
$('#orderform').submit(function(e) {
if(!$.trim($(this).find('input[type="text"]').val()).length){
e.preventDefault();
alert('Please fill all the fields');
}
});

HTML Form Validation via Javascript

I want to keep viewers from entering words like "fssadf", and force them to enter a valid email which must contain the "#" in the middle and "." to prevent spam and injection.
I also want the form to display an error message that says "change the email field to the correct email"
I use js_function.js which contain this:
function validEmail()
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
but it does not prevent the viewer from sending me "sfdasfd" instead of a valid email.
What can I do to achieve the above?
check out the files below:
http://www.mediafire.com/?kx5bvttc0s2fbrs
thanks,
rami
Though I didn't see any error on my program what you provided but still you may
use
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
instead of this
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
I think that will help. I provided the total Javascript code what worked properly for me.
function validEmail()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
Use this
or you may use this too in other way
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate(this.value)" />
//Other Codes
</form>
And Javascript
<script>
function validate(email)
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
OR
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
And the last solution will be quiet easier to apply I think.
Error Message on Page instead of Popup
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
<span id="errormessage"></span>
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
document.getElementById('errormessage').innerHTML= 'fill your email';
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
document.getElementById('errormessage').innerHTML= '';
return true;
}
}
</script>
try with this
$(document).ready(function() {
$('#btn-submit').click(function() {
$(".error").hide();
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#UserEmail").val();
if(emailaddressVal == '') {
$("#UserEmail").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if(!emailReg.test(emailaddressVal)) {
$("#UserEmail").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
}
if(hasError == true) { return false; }
});
});
Duplicate of this question:
Validate email address in JavaScript?
There is some valuable discussion in the comments about edge cases that SHOULD NOT be ignored.
Did you try to Google this one before you asked? IT is a /very/ common question.
If you're after a pure HTML5 solution using jQuery.... Here's a live demo
HTML
<form id="form">
Email <input name="field1" required="required" type="email" /> <br />
<div id="error"></div>
<input required="required" name="submit" type="submit" />
</form>​
Code
$(document).ready(function() {
var validCheckInput = function() {
if ($(this)[0].checkValidity()) {
$(this).removeClass("error");
$("#error").empty();
} else {
$(this).addClass("error");
$("#error").text("change the email field to the correct email");
}
if ($("#form")[0].checkValidity()) {
$("#form input[type='submit']").removeAttr("disabled");
} else {
$("#form input[type='submit']").attr("disabled", "disabled");
}
};s
var binds = function(validCheck) {
$(this).change(validCheck);
$(this).focus(validCheck);
$(this).keyup(validCheck);
validCheck.call($(this));
}
$("#form input").each(function() {binds.call(this, validCheckInput)});
});​
CSS
.error {
border: 2px solid red;
}​

Single else clause for multiple if clauses - javascript

First: I'm JavaScript newbie.
So.. I have basic form with password, repeat password, email and repeat email fields. I want to check if password is equal to repeat password. If it's not, alert message appears and page reloads. Same for email and repeat email.
BUT if pass and repeat password aren't equal AND email and repeat email aren't equal, first alert message appears, then the second message (this time for email) appears too fast. I want to show only one alert message when both fields don't match.
<script type="text/javascript">
function checkFields() {
var pass= document.getElementById('password');
var reppass= document.getElementById('reppass');
var email= document.getElementById('email');
var repemail= document.getElementById('repemail');
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
}
else if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
}
</script>
And the form:
<form onSubmit="checkFields()">
<p><label>Password:</label> <input name="password" id="password" required="true" type="password" /></p>
<p><label>Repeat password:</label> <input name="reppass" id="reppass" required="true" type="password" /></p>
<p><label>Email:</label> <input name="email" id="email" required="true" type="email" /></p>
<p><label>Repeat Email:</label> <input name="repemail" id="repemail" required="true" type="email" /></p>
<p><input type="submit" value="Send"></p>
</form>
You can simply return from the if clauses like this:
function checkFields() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
return;
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
return;
}
}
I like this style, because it prevents nesting if clauses. The downside is, that you have multiple return points that can be confusing - this heavily depends on the length of the function.
EDIT
Updated order of if blocks
if( condition1 ) {
}else if( condition2 ) {
}else{
…
}
I believe this is what you want.
One solution would be to break the validation up into separate methods, then only run the second validation if the first one succeeds.
Here's an example:
var FormValiditor = function() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
return {
checkFields: function() {
if(checkPassword()){
return checkEmail();
}
return false;
},
checkPassword: function() {
if (pass.value != reppass.value) {
alert("Password don't match");
return false;
}
return true;
},
checkEmail: function() {
if(email.value != repemail.value){
alert("Emails do not match");
return false
}
return true
}
}
}();
Then, if you're using jQuery(which you should be!) you can run validation when the form gets submitted.
$('form').submit(FormValidator.checkFields);
if ...
else if ...
else if ...
...
else ...
That's how it should be structured. You can have as many else ifs as you like.

Categories

Resources