I have created a web page using bootstrap. There are 2 text boxes and a button to submit. I have written JavaScript function to give an alert if any text field is empty. I am amazed to see that it is not working. My JavaScript function is:
function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
return false;
}else if (a==null || a=="")
{
alert("Field 1 is required");
return false;
}else if (b==null || b=="")
{
alert("Field 2 is required");
return false;
}else if(a!="" && b!="")
{
alert("Submitted Successfully");
return true;
}
}
My form code is:
<form role="form" method="post" name="Form" onsubmit="return validateForm()">
<div class="row 150%">
<div class="6u 12u$(medium)">
<input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
</div>
<div class="6u 12u$(medium)">
<input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
</div>
</div><br /><br />
<button id="submit" class="button" style="vertical-align:middle">
<span>Submit </span>
</button>
</form>
How have you included the validateForm javascript?
for instance the following works for me:
<html>
<body>
<script>
function validateForm()
{
var a=document.forms["Form"]["field1"].value;
var b=document.forms["Form"]["field2"].value;
if(a=="" && b=="")
{
alert("Both fields are required");
return false;
}else if (a==null || a=="")
{
alert("Field 1 is required");
return false;
}else if (b==null || b=="")
{
alert("Field 2 is required");
return false;
}else if(a!="" && b!="")
{
alert("Submitted Successfully");
return true;
}
}
</script>
<form role="form" method="post" name="Form" onsubmit="return validateForm()">
<div class="row 150%">
<div class="6u 12u$(medium)">
<input class="form-control" name="field1" id="ex1" type="text" autofocus placeholder="First Text Field">
</div>
<div class="6u 12u$(medium)">
<input class="form-control" name="field2" id="ex2" type="text" autofocus placeholder="Second Text Field">
</div>
</div><br /><br />
<button id="submit" class="button" style="vertical-align:middle">
<span>Submit </span>
</button>
</form>
</body>
</html>
Related
Sorry this might be a duplicate Q , but could not find a direct solution easily,
I have gone through SO answer and found , enable submit if all values are filled ,
$(document).ready(function() {
$('.field input').keyup(function() {
var empty = false;
$('.field input').each(function() {
if ($(this).val().length == 0) {
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').attr('disabled', false);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='form'>
<form>
<div class='field'>
<label for="username">Username</label>
<input id="username" type="text" />
</div>
<div class='field'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='actions'>
<input type="submit" value="Login" disabled="disabled" />
</div>
</form>
</div>
But how to achieve the same(enable submit) if atleast one field is non-empty
You can try this:
$(document).ready(function() {
$('.field input').keyup(function() {
var hasValue = $('#username,#password').filter((index, input) => input.value.length > 0).length;
$('.actions input').attr('disabled', hasValue ? false : 'disabled');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='form'>
<form>
<div class='field'>
<label for="username">Username</label>
<input id="username" type="text" />
</div>
<div class='field'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='actions'>
<input type="submit" value="Login" disabled="disabled" />
</div>
</form>
</div>
Update:
$('#username,#password').filter((index, input) => input.value.length > 0).length
This line means we will check the value of the 2 input elements username and password, if all of them don't have any value, the button will be disabled. If you want to check another input element before enabling/disabling, you can add:
$('#username,#password,#input_3,#input_4').filter(...).length
By this way, the button will be disabled when username, password, input_3 and input_4 elements don't have any value. Make sure you have a specific id for each input element.
Update 2:
Checking for both username and password have some value:
var hasValue = $('#username,#password').filter((index, input) => input.value.length > 0).length === 2
Checking for field, field4 and field5 have some value:
var hasValue = $('#field,#field4,#field5').filter((index, input) => input.value.length > 0).length === 3
Use jQuery props method.
$(document).ready(function() {
$(':input[type="submit"]').prop('disabled', true);
$('input').keyup(function() {
if($(this).val() != '') {
$(':input[type="submit"]').prop('disabled', false);
}else{
$(':input[type="submit"]').prop('disabled', true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='form'>
<form>
<div class='field'>
<label for="username">Username</label>
<input id="username" type="text" />
</div>
<div class='field'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='actions'>
<input type="submit" value="Login" disabled="disabled" />
</div>
</form>
</div>
Another way to go about it:
Store the fields, and create a new collection of them each time a key is pressed, filtering each one by its value.
If the length of our empty fields is the same as the length of all fields, disable the button:
$(document).ready(function() {
var $fields = $('.field input');
$fields.keyup(function() {
var $emptyFields = $fields.filter(function(){
return !this.value;
});
$('.actions input').prop('disabled', $emptyFields.length === $fields.length);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='form'>
<form>
<div class='field'>
<label for="username">Username</label>
<input id="username" type="text" />
</div>
<div class='field'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='actions'>
<input type="submit" value="Login" disabled="disabled" />
</div>
</form>
</div>
Documentation:
.filter()
.prop()
You could with Jquery.map and Array.find
Jquery.map().get() is get all the input value length with condition.
Array.find will find the any one of the input as valid length of string
Then finally the result will be reversely compare prop('disabled', !filled)
$(document).ready(function() {
$('.field input').keyup(function() {
var res = $('.field input').map(function() {
return $(this).val().length != 0
}).get()
var filled = res.find(a=> a == true)
$('.actions input').prop('disabled', !filled);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='form'>
<form>
<div class='field'>
<label for="username">Username</label>
<input id="username" type="text" />
</div>
<div class='field'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='actions'>
<input type="submit" value="Login" disabled="disabled" />
</div>
</form>
</div>
Updated with select option
Required field based .Button only enabled after required field 1 and 3 both are filled
$(document).ready(function() {
$('.field input,.field select').on('keyup change',function() {
var res = $('.field input[required],.field select[required]').map(function() {
return $(this).val().trim().length != 0
}).get();
var filled = res.every(a => a == true)
$('.actions input').prop('disabled', !filled);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='form'>
<form>
<div class='field'>
<label for="username">Username *</label>
<input id="username" required type="text" />
</div>
<div class='field'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='field'>
<label for="password">email *</label>
<input id="password" required type="password" />
</div>
<div class='field'>
<label for="password">select email *</label>
<select required>
<option value="">Select</option>
<option value="1">one</option>
<option value="2">two</option>
</select>
</div>
<div class='actions'>
<input type="submit" value="Login" disabled="disabled" />
</div>
</form>
</div>
You can try this in a simple way, as shown below:
var filled = false;
$('.field input').each(function() {
if ($(this).val().length > 0) {
filled = true;
return; // just add return means break from loop whenever any field is filled.
}
});
if (filled) {
$('.actions input').attr('disabled', false);
} else {
$('.actions input').attr('disabled', 'disabled');
}
});
how to show the result of First name and email in popup window.open.
example :
Congratulations!
Name :
EMail :
function validateForm()
{
var ufname=document.forms["regform"]["fname"].value;
var uemail=document.forms["regform"]["email"].value;
if (ufname=="" || uemail=="")
{
alert("PLEASE ENTER THE VALUES!");
return false;
}
}
<form method="post" name="regform" id="regform" onsubmit="return validateForm()">
<label>First name </label>
<input type="text" name="fname" id="fname" placeholder="Your Name">
<label>Email Address </label>
<input type="text" name="email" id="email" placeholder="hi#domain.com">
<button type="submit" value="submit">Register</button> <input type="reset" value="Reset">
</form>
If you want to do with new window try this by using window.open
function validateForm()
{
var ufname=document.forms["regform"]["fname"].value;
var uemail=document.forms["regform"]["email"].value;
if (ufname=="" || uemail=="")
{
alert("PLEASE ENTER THE VALUES!");
return false;
}
else
{
var myWindow = window.open("", "RegisterWindow", "width=200,height=100");
myWindow.document.write("<p>Congratulations! </p> <p>Name : "+ufname+".</p><p>EMail : "+ uemail +".");
}
}
<form method="post" name="regform" id="regform" onsubmit="return validateForm()">
<label>First name </label>
<input type="text" name="fname" id="fname" placeholder="Your Name">
<label>Email Address </label>
<input type="text" name="email" id="email" placeholder="hi#domain.com">
<button type="submit" value="submit">Register</button> <input type="reset" value="Reset">
</form>
try
function validateForm()
{
var ufname=document.forms["regform"]["fname"].value;
var uemail=document.forms["regform"]["email"].value;
if (ufname=="" || uemail=="")
{
alert("PLEASE ENTER THE VALUES!");
return false;
} else {
var popupWindow = window.open('');
popupWindow.document.body.innerHTML = '<div>Your Name: '+ufname+'</div><div>Your Email: '+uemail+'</div>'
}
}
There is a form on my page where I want to display a check mark(tick) right beside all input fields. I've already tried a couple of ways to do this but unable to achieve what I want.Below is my code....
$(document).ready(function() {
$("#myForm").on('submit', function(event) {
event.preventDefault();
var firstName = $('#first').val();
var lastName = $('#last').val();
var email = $('#email').val();
var pass = $('#password').val();
if (firstName == "") {
$('#first-name-error').text("Please enter your first name");
} else if (firstName.length > 0) {
$(this).next().show();
}
if (lastName == "") {
$('#last-name-error').text("Please enter your last name");
}
if (email == "") {
$('#email-error').text("Please enter your email address");
} else if (email == "aisha_salman3#outlook.com") {
$('#email-error').text("This email is already taken!");
}
if (pass == "") {
$('#password-error').text("Please enter your password");
} else if (pass.length < 8) {
$('#password-error').text("Short passwords are too easy to guess.Try one with at least 8 characters");
}
});
});
.tick {
background: url(images/done-tick.png) no-repeat;
width: 20px;
height: 20px;
position: absolute;
margin: 5px 20px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-3">
<form id="myForm" action="" method="">
<fieldset>
<legend>Create Account</legend>
<div class="form-group">
<label for="first">First Name</label>
<p id="first-name-error"></p>
<input type="text" class="form-control" id="first" maxlength="10" placeholder="your first name ..." autofocus />
<span class="tick"></span>
</div>
<div class="form-group">
<label for="last">Last Name</label>
<p id="last-name-error"></p>
<input type="text" class="form-control" id="last" maxlength="10" placeholder="your last name ..." />
<span class="tick"></span>
</div>
<div class="form-group">
<label for="email">Email</label>
<p id="email-error"></p>
<input type="email" class="form-control" id="email" placeholder="your email ..." />
<span class="tick"></span>
</div>
<div class="form-group">
<label for="password">Password</label>
<p id="password-error"></p>
<input type="password" class="form-control" id="password" placeholder="your password ..." />
<span class="tick"></span>
</div>
</fieldset>
<input class="btn" type="submit" value="Sign Up " />
</form>
</div>
</div>
</div>
</main>
Please guide me.Thank you!
You seem to be referencing this, which is the form element, not the first name. So when you get next, you are not getting an element. Your code should look like:
if (firstName == "") {
$('#first-name-error').text("Please enter your first name");
} else if (firstName.length > 0) {
$('#first').next().show();
}
Here is a fiddle to show how it works. https://jsfiddle.net/ukg82xqr/2/
Basically, I want to prepend a div only if the div I'm prepending isn't already showing.
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error");
if (!username || !password && errorvisible == false) {
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$('.error.alert').remove();
});
}, 6000);
event.preventDefault();
}
});
At the moment, I'm trying to make it so the jquery will only do the if empty if statement if the error isn't currently visible however it's not working...
<div class="pageCont">
<div class="title">
<h1>LetsChat</h1>
<h4>The new way of interaction.</h4>
</div>
<div class="login box">
<form method="POST" action="#" class="loginForm">
<input type="text" class="loginInput username" placeholder="Aquinas Email or Number" /><br>
<input type="password" class="loginInput password" placeholder="Password" /><br>
<div class="checkBox">
<input type="checkbox" id="checkBoxLink">
<label for="checkBoxLink">Remember Me</label>
Forgotten your password?
</div>
<input type="submit" value="Submit" class="login btn green" />
<input type="reset" value="Clear Fields" class="reset btn green" />
</form>
</div>
<div class="signup box">
<form method="POST" action="#" class="signupForm">
<input type="text" class="signupInput" placeholder="First Name" /><br>
<input type="text" class="signupInput" placeholder="Last Name" /><br>
<input type="text" class="signupInput" placeholder="Aquinas Email" /><br>
<input type="password" class="signupInput" placeholder="Password" /><br>
<input type="submit" class="purple btn signup" value="Sign Up Today!">
</form>
</div>
</div>
The below should work if I'm understanding your question correctly?
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error").length;
if (!username || !password)
{
if(errorvisible == 0)
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$('.error.alert').remove();
});
}, 6000);
event.preventDefault();
}
});
I have used this type of code many times:
if(!$('#myFancyDiv').is(':visible')) {
//prepend or do whatever you want here
}
BTW just for clarity, this code checks if 'myFancyDiv' is not visible.
You can check whether the .error.alert elements exists, if so don't do anything else create a new one
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error");
if (!username || !password && errorvisible == false) {
if (!$('.error.alert').length) {
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$(this).remove();
});
}, 6000);
}
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="#" class="loginForm">
<input type="text" class="loginInput username" placeholder="Aquinas Email or Number" />
<br>
<input type="password" class="loginInput password" placeholder="Password" />
<br>
<div class="checkBox">
<input type="checkbox" id="checkBoxLink">
<label for="checkBoxLink">Remember Me</label>
Forgotten your password?
</div>
<input type="submit" value="Submit" class="login btn green" />
<input type="reset" value="Clear Fields" class="reset btn green" />
</form>
ami i doing something wrong here? I am trying to run a small piece of validation bny using javascript. Am I doing the regular expressions correctly?
var z=document.forms["myForm"]["website"].value;
if (z==null || z=="")
{
$('.five').show();
return false;
}
var validWebsite = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
if(!validWebsite.test(document.forms["myForm"]["website"].value))
{
$('.five').html('Enter a Valid Website');
return false;
}
var number = /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/
if(!number.test(document.forms["myForm"]["number"].value)){
$('.six').show()
return false;
}
html
*email: <br>
<input type="text" name="email"/><div class="four alertmessage" style="display:none;color:red;">Enter your Email</div><br>
website: <br>
<input type="text" name="website"/><div class="five alertmessage" style="display:none;color:red;">Enter your Website</div><br>
Contact phone number: <br>
<input type="text" name="number"/><div class="six alertmessage" style="display:none;color:red;">Enter your Number</div>
<input name="submit" class="submitButton" type="submit" value="Submit">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function validate()
{
var z=document.forms["myForm"]["website"].value;
if (z=="")
{
$('.five').show();
return false;
}
var validWebsite = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if(!validWebsite.test(z)){
$('.five').html('Enter a Valid Website');
return false;
}
var n=document.forms["myForm"]["number"].value;
var number = /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/;
if(!number.test(n)){
$('.six').show()
return false;
}
return true;
}
</script>
<form onsubmit="return validate()" method="post" name="myForm">
*email: <br>
<input type="text" name="email"/><div class="four alertmessage" style="display:none;color:red;">Enter your Email</div><br>
website: <br>
<input type="text" name="website"/><div class="five alertmessage" style="display:none;color:red;">Enter your Website</div><br>
Contact phone number: <br>
<input type="text" name="number"/><div class="six alertmessage" style="display:none;color:red;">Enter your Number</div>
<input name="submit" class="submitButton" type="submit" value="Submit">
</form>