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/
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');
}
});
I started to learn javascript and there was such a question. How to insert a message in a div when the form is filled is not correct? I've seen similar questions where innerHTML was used, but trying to translate it into my application, I did not get anything, the message is not output. Where could I be wrong?
var namePattern = new RegExp("^([A-z]{4,20})$");
var emailPattern = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,5})$");
var passwordPattern = new RegExp("^[A-z0-9]{4,20}$");
document.getElementById("registration_form").addEventListener("submit", function(event) {
var fName = document.getElementById("fName").value;
var lName = document.getElementById("lName").value;
var email = document.getElementById("email").value;
var password = document.getElementById("pass").value;
var confirmPassword = document.getElementById("confPass").value;
if (!namePattern.test(fName)) {
document.getElementById("error_first_name").innerHTML = 'Wrong first name';
event.preventDefault();
} else if (!namePattern.test(lName)) {
document.getElementById("error_last_name").innerHTML = 'Wrong last name';
event.preventDefault();
} else if(!emailPattern.test(email)){
document.getElementById("error_email").innerHTML = 'Wrong email';
event.preventDefault();
} else if(!passwordPattern.test(password)){
document.getElementById("error_password").innerHTML = 'Wrong password';
event.preventDefault();
} else if(confirmPassword != password){
document.getElementById("error_confirmPassword").innerHTML = ''
event.preventDefault();
}
})
<form action="" method="post" id="registration_form">
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<span>First Name<label>*</label></span>
<div id="error_first_name" style="color: #ff0000"></div>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<span>Last Name<label>*</label></span>
<div id="error_last_name" style="color: #ff0000"></div>
<input type="text" name="lName" id="lName" placeholder="Your last name" >
</div>
<div>
<span>Email Address<label>*</label></span>
<div id="error_email" style="color: #ff0000"></div>
<input type="text" name="eMail" id="email" placeholder="Your email" >
</div
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="register-bottom-grid">
<h3>LOGIN INFORMATION</h3>
<div>
<span>Password<label>*</label></span>
<div id="error_password" style="color: #ff0000"></div>
<input type="password" name="password" id="pass" placeholder="Your password">
</div>
<div>
<span>Confirm Password<label>*</label></span>
<div id="error_confirmPassword" style="color: #ff0000"></div>
<input type="password" name="confirmPassword" id="confPass" placeholder="Confirm your password">
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
There are a couple of things that were wrong.
First, there is nothing triggering the form submit for which I added a button that will submit the form.
Second event.preventDefault is function.
I corrected the above two and your form is now submitting. (Also take a look at regex I think it is not correct)
var namePattern = new RegExp("^([a-z]{4,20})$");
document.getElementById("registration_form").addEventListener("submit", function(event) {
var fName = document.getElementById("fName").value;
var lName = document.getElementById("lName").value;
if (!namePattern.test(fName)) {
document.getElementById("error_first_name").innerHTML = 'Wrong first name';
event.preventDefault();
} else if (!namePattern.test(lName)) {
document.getElementById("error_last_name").innerHTML = 'Wrong last name';
event.preventDefault();
}
}, false)
<form action="" method="post" id="registration_form">
<div class="register-top-grid">
<h3>PERSONAL INFORMATION</h3>
<div>
<div id="error_first_name" style="color: #ff0000"></div>
<span>First Name<label>*</label></span>
<input type="text" name="fName" id="fName" placeholder="Your first name">
</div>
<div>
<div id="error_last_name" style="color: #ff0000"></div>
<span>Last Name<label>*</label></span>
<input type="text" name="lName" id="lName" placeholder="Your last name">
</div>
<button type="submit">Submit</button>
</form>
JS:
var namePattern = new RegExp("^([A-z]{4,20})$");
document.getElementById("registration_form").addEventListener("submit", function(event){ //you have a syntax error here
//you need to prevent the page reload after submitting the form
event.preventDefault();
var fName = document.getElementById("fName").value;
var lName = document.getElementById("lName").value;
if(!namePattern.test(fName)){
document.getElementById("error_first_name").innerHTML = 'Wrong first name';
event.preventDefault;
}else if(!namePattern.test(lName)){
document.getElementById("error_last_name").innerHTML = 'Wrong last name';
event.preventDefault;
}
}) //don't forget the closed parenthese
Output:
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>
So I have been working on a simple script for a class project. I am a new javascript student so this i giving me a hard time even though I think it can be solved easy. We the form is submitted, I input a 7 and get "wrong answer" which is good, but then I input 8 (correct answer) and it still outputs wrong answer. I do not know why it cannot differentiate any other number from 8. Please help
$("#story").submit(function (e) {
var answer = document.getElementById('human-story');
if (answer != 8) {
console.log(answer);
e.preventDefault();
}else {
alert("right answer");
e.preventDefault();
}
})
<form class="form-horizontal contact" name="contact" method="post" action="" id="story">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4>We are excited to hear your story!</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="contact-name" class="col-lg-2 control-label">Name:</label>
<div class="col-lg-10">
<input type="text" name="first_name" class="form-control" id="contact-name" placeholder="First & Last Name" required="" >
</div>
</div>
<div class="form-group">
<label for="contact-email" class="col-lg-2 control-label">Email:</label>
<div class="col-lg-10">
<input type="email" name="email" class="form-control" id="contact-email" placeholder="you#example.com" required="">
</div>
</div>
<div class="form-group">
<label for="contact-message" class="col-lg-2 control-label">Story:</label>
<div class="col-lg-10">
<textarea name="message" rows="8" class="form-control" style="resize:none;" required=""></textarea>
</div>
</div>
<div class="form-group">
<label for="human" class="col-sm-2 control-label">5 + 3 = ?</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="human-story" name="human-story" placeholder="Your Answer" required="">
</div>
</div>
</div>
<div class="modal-footer">
Close
<button class="btn btn-success" name="submit-story" type="submit-story" value="Send!">Send</button>
</div>
</form>
You have more than one field with .form-controll class. Use id attribute to define which field have to be checked for the right answer:
$("#story").submit(function (e) {
e.preventDefault();
if ($("#human-story").val() == '8') {
alert("right answer");
} else {
alert("wrong answer");
}
});
Having multiple elements with form-controll class, using $(".form-controll").val() , jQuery returns value of the very first element with given class (in your case it's "name" field value).
use like this
$("#story").submit(function (e) {
if ($(".form-control").val() == '8') {
alert("right answer");
}else {
alert("wrong answer");
}
e.preventDefault();
});
first you can put e.preventDefault(); directly before you're setting the variable.
so you just have to write it once.
and y you don't just turn the if clause to
$("#story").submit(function (e) {
e.preventDefault();
var answer = parseInt($(".form-control").val(), 10);
if (answer == 8) {
alert("right answer");
} else {
alert("wrong answer");
}
});
see working fiddle:
$("#story").submit(function(e) {
e.preventDefault();
var answer = parseInt($(".form-control").val(), 10);
if (answer == 8) {
alert("right answer");
} else {
alert("wrong answer");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="story">
<input name="form--control" type="text" class="form-control" />
<input name="submit" type="submit" class="form--submit" />
</form>
I need to use unobtrusive javascript/jquery to check if input fields have been filled out. If they are I need to display what input field that was. Not the value.
Here is the input form
<div class="inputCol">
<div class="formItem first-name">
<label>First Name:</label>
</div>
<div class="inputCol">
<input maxlength="40" size="35" id="firstName" name="firstName" class="imput_value" type="text" />
</div>
<div class="formItem last-name">
<label>Last Name:</label>
</div>
<div class="inputCol">
<input maxlength="40" size="35" id="lastName" name="lastName" class="imput_value" type="text" />
</div>
<div class="formItem email">
<label>Email:</label>
</div>
<div class="inputCol">
<input maxlength="40" size="35" id="email" name="email" class="imput_value" type="text" />
</div>
<div class="inputCol">
submit
</div>
So on click of the submit button I need it to alert "First Name, Email" if just the first name and email had input in them. These inputs do not need to be validated. As long as the field is not empty it should display that that input has been submitted.
This is the code I currently have, don't really know where to go from here:
$('a.submit_button').click(function(){
var validate= false;
$('input.imput_value').each(function(){
if($(this).val() != '' || $(this).attr('checked'))
validate = true;
});
if(validate){
var dataFilled = $(this).closest('.formItem').find('input').text().trim();
alert(dataFilled);
return false;
}
});
$('a.submit_button').click(function(){
var filledInputs = '';
$('input.imput_value').each(function(){
if($(this).val() !== '' || $(this).attr('checked')){
filledInputs += $(this).attr('name') + ', ';
}
});
if(filledInputs !== ''){
alert(filledInputs);
}
});
Should do what you want.