Adding classes during runtime to html elements not working as expected - javascript

I am trying to create a form with some basic client side validation. In the form i have 3 input fields for, username, email and password. Initially they have a common class that is input. Also i attached a sibling paragraph element to these input elements, these paragraph element contains some input specification that has to be displayed to user if user enters something invalid.
In CSS i have basically created two classes, valid and invalid, valid just turns the border of input elements to green, and invalid turns border to red and sets the paragraph element opacity to 1 from 0(initial style).
In script file to check validity of user's input i have three boolean variables, isUserNameValid, isEmailValid, isPasswordValid, all these three are initially set to false.
Now i am adding these CSS classes during runtime as user inputs. Adding classes (valid and invalid) is working fine for first input element that is username input element, but as soon as i go to next input element that is email and type a single letter, script is adding class valid to email input element instead of invalid, even though isEmailValid is false.
I tried my best to figure out why it's adding class valid even though i am explicitly saying if the isEmailValid is equals to false add a class of invalid and remove class valid, instead it's doing the opposite.
I have attached the fiddle link, also i am not very much experienced in JavaScript, so, explanation in simple English is appreciated.
if(username.length > 5) {
isUserNameValid = true
}
if(email.length > 10) {
isEmailValid = true
}
if(password.length > 10) {
isPasswordValid = true
}
if(isUserNameValid === true && isEmailValid === true && isPasswordValid === true) {
loginButton.disabled = false
loginButton.style.cursor = 'pointer'
} else {
console.log('username',username, isUserNameValid)
console.log('email',email, isEmailValid)
console.log('password',password, isPasswordValid)
loginButton.disabled = true
loginButton.style.cursor = 'default'
if(isUserNameValid === false) {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if(isEmailValid === false) {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if(isPasswordValid === false) {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if(isUserNameValid === true) {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
if(isEmailValid === true) {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
if(isPasswordValid === true) {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
}
FIDDLE LINK: https://jsfiddle.net/weg9jy0c/5/

will this work for you?
https://jsfiddle.net/gnca42xp/1/
const form = document.querySelector('.main-form')
form.addEventListener('keyup', (e) => {
const loginButton = document.querySelector('.login-btn')
const username = document.querySelector('#name').value
const email = document.querySelector('#email').value
const password = document.querySelector('#password').value
let isUserNameValid = false;
let isEmailValid = false;
let isPasswordValid = false;
currentUpdateField = e.target.getAttribute('id');
if (username.length > 5) {
isUserNameValid = true
}
if (email.length > 10) {
isEmailValid = true
}
if (password.length > 10) {
isPasswordValid = true
}
if (isUserNameValid === true && isEmailValid === true && isPasswordValid === true) {
e.target.classList.remove('invalid')
loginButton.disabled = false
loginButton.style.cursor = 'pointer'
} else {
console.log('username', username, isUserNameValid)
console.log('email', email, isEmailValid)
console.log('password', password, isPasswordValid)
loginButton.disabled = true
loginButton.style.cursor = 'default'
if (isUserNameValid === false && currentUpdateField === 'name') {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if (isEmailValid === false && currentUpdateField === 'email') {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if (isPasswordValid === false && currentUpdateField === 'password') {
e.target.classList.add('invalid')
e.target.classList.remove('valid')
}
if (isUserNameValid === true && currentUpdateField === 'name') {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
if (isEmailValid === true && currentUpdateField === 'email') {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
if (isPasswordValid === true && currentUpdateField === 'password') {
e.target.classList.add('valid')
e.target.classList.remove('invalid')
}
}
})
.input {
outline: none;
}
.valid {
border: 1px solid rgb(89, 224, 89);
}
input+p {
opacity: 0;
}
.invalid {
border: 2px solid rgb(245, 101, 101);
}
input.invalid+p {
opacity: 1;
color: orange;
}
<html>
<title>Demo Form</title>
<body>
<form class="main-form" method="post">
<input class="input" type="text" name="username" id="name" placeholder="Username">
<p>Username must have more than 5 characters</p>
<input class="input" type="email" name="email" id="email" placeholder="Email">
<p>Email must of format <b>email#site.domain</b></p>
<input class="input" type="password" name="password" id="password" placeholder="Password">
<p>Password must have more than 5 characters and aplhanumeric with a special character</p><br>
<button type="submit" class="login-btn" disabled>Register</button>
</form>
</body>
</html>
What happens in your case
1) First user enters data in username it is valid after 5 characters
2) then user enters data in email field, here e.target is email field, but as from your code, isUsernameInvalid is defined false, and added class to e.target which is email field.
That is why your code is not working
So what i have done is,
I am getting id on the current updating field, and then adding or removing classes only if id matches

Related

Enable Submit after password validation

In Profile Section of the user the password field is not mandatory however I set a function which calls the password validation.
Password and Confirm Password Field
<input type="password" id="password" name="password" class="form-control" onfocus="submission()">
<input type="password" id="cpassword" name="password_confirmation" class="form-control" onfocus="submission()">
Submission JS Function
function submission() {
$(':input[type="submit"]').prop('disabled', true);
$('input[type="password"]').keyup(function() {
if(passwordValidation()) {
$(':input[type="submit"]').prop('disabled', false);
}
});
}
Password Validation Function
function passwordValidation() {
$('input[type=password]').keyup(function() {
var pswd = $(this).val();
if (pswd != '') {
var x = document.getElementById("password").value;
var y = document.getElementById("cpassword").value;
if ( pswd.length < 8 ) {
$('#length').removeClass('valid').addClass('invalid');
} else {
$('#length').removeClass('invalid').addClass('valid');
}
//validate letter
if ( pswd.match(/[A-z]/) ) {
$('#letter').removeClass('invalid').addClass('valid');
} else {
$('#letter').removeClass('valid').addClass('invalid');
}
//validate capital letter
if ( pswd.match(/[A-Z]/) ) {
$('#capital').removeClass('invalid').addClass('valid');
} else {
$('#capital').removeClass('valid').addClass('invalid');
}
//validate number
if ( pswd.match(/\d/) ) {
$('#number').removeClass('invalid').addClass('valid');
} else {
$('#number').removeClass('valid').addClass('invalid');
}
//validate symbol
if ( pswd.match(/[!##$%^&*]/) ) {
$('#symbol').removeClass('invalid').addClass('valid');
} else {
$('#symbol').removeClass('valid').addClass('invalid');
}
//validate symbol
if ( x == y && x != "" && y != "" ) {
$('#confirm').removeClass('invalid').addClass('valid');
} else {
$('#confirm').removeClass('valid').addClass('invalid');
}
return true;
} else {
return false
}
}).focus(function() {
$('#pswd_info').show();
}).focusout(function() {
$('#pswd_info').hide();
});
//return true;
}
The return of passwordValidation() is allows undefined not getting any false or true result. I tried multiple ways but no luck of success, anyone can help telling me what's wrong with the code.
The process of the password check is as following.
User should pass all conditions to turn on green then the submit button will be enabled otherwise if one or multiple conditions are not matched the submit button will be disabled. And if the inputs are empty it will be disabled as well. I don't want to allow the submission before setting the right password and confirming it.

How can this Javascript code handle the if/else statements better, or possibly use switches?

First off, if this is against the rules, or frowned upon I'm very sorry and feel free to downvote/close. I'm desperately stuck.
I'm having trouble with an HTML page I wrote which is supposed to consist of inputs with certain requirements, adding div's to display error messages , and automatically update those error messages onblur. The assignment was made to test our javascript skills, and thus must be completely validated through javascript.
Here are a few of the guidelines...
validating the form for four separate things:
presence of required fields
equality of password fields
conformance to a password policy (one uppercase, one number, length > 7)
validity of the email address
When any one of these are violated, I should deactivate the form’s submit button so that it is not clickable and add a child "div" to the error-display containing an error message describing the situation.
The code seems correct to me, and works spontaneously, but i believe since javascript is looked at one line at a time it isn't displaying error messages correctly or even getting to certain parts of my code at all.
Here is my large chunk of javascript code, I am mainly looking for a way to break out of these if/else blocks that my code seems stuck in:
function formValidation() {
var form = document.getElementById('project-form');
var username = document.getElementById('username');
var name = document.getElementById('name');
var phone = document.getElementById('phone-number');
var email = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirmation = document.getElementById('password-confirmation');
var submit = document.getElementById('submit-btn');
var errorDisplay = document.getElementById('error-display');
var missingFieldBoolean = false;
var passwordMismatchBoolean = false;
var isUpper = false;
var isNumber = false;
var passwordLength = false;
var validEmail = false;
var createDiv = document.createElement("DIV");
var passwordConstraint, passwordConstraintError;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
//Checks all fields for empty values and updates error div
if (username.value.length == 0 || name.value.length == 0 || email.value.length == 0 || password.value.length == 0 || passwordConfirmation.value.length == 0) {
missingField = errorDisplay.appendChild(createDiv);
missingField.setAttribute("id", "required-field-error");
missingFieldError = document.getElementById('required-field-error');
missingFieldError.innerHTML = "Missing Fields: ";
if (username.value.length == 0) {
missingFieldError.innerHTML += "Username - ";
}
if (name.value.length == 0) {
missingFieldError.innerHTML += "Full Name - ";
}
if (email.value.length == 0) {
missingFieldError.innerHTML += "Email - ";
}
if (password.value.length == 0) {
missingFieldError.innerHTML += "Password - ";
}
if (passwordConfirmation.value.length == 0) {
missingFieldError.innerHTML += "Password Confirmation - ";
}
} else {
errorDisplay.removeChild(missingFieldError);
missingFieldBoolean = true;
}
//Checks password vs password confirmation to see if they match, else updates error div
if (password.value != passwordConfirmation.value) {
passwordMismatch = errorDisplay.appendChild(createDiv);
passwordMismatch.setAttribute("id", "password-mismatch-error");
passwordMismatchError = document.getElementById('password-mismatch-error');
passwordMismatchError.innerHTML = "The Password and Password Confirmation do not match. Please re-enter.";
} else {
errorDisplay.removeChild(passwordMismatchError);
passwordMismatchBoolean = true;
}
//for loop to iterate through password to check for required characters, else updates error div
for (var index = 0; index < password.value.length; index++) {
if (password.value.charAt(index) == password.value.charAt(index).toUpperCase) {
isUpper = true;
}
if ("0123456789".indexOf(password.value.charAt(index)) > -1) {
isNumber = true;
}
if (password.value.length > 7) {
passwordLength = true;
} else {
passwordConstraint = errorDisplay.appendChild(createDiv);
passwordConstraint.setAttribute("id", "password-constraint-error");
passwordConstraintError = document.getElementById('password-constraint-error');
passwordConstraintError.innerHTML = "The Password must be 8 characters long, with one uppercase letter and one number. ";
}
}
//checks if password constraints are met and removes div if true
if (isUpper && isNumber && passwordLength) {
errorDisplay.removeChild(passwordConstraintError);
}
//checks email, if invalid it adds error div, else it removes the div ***NOT WORKING***
if (!(mailformat.test(email.value))) {
invalidEmail = errorDisplay.appendChild(createDiv);
invalidEmail.setAttribute("id", "invalid-email-error");
invalidEmailError = document.getElementById('invalid-email-error');
invalidEmailError.innerHTML = "Please enter a valid email address.";
} else {
errorDisplay.removeChild(invalidEmailError);
validEmail = true;
}
//if all requirements are met and true, submit button becomes enabled ***NOT WORKING***
if (isUpper && isNumber && passwordLength && missingFieldBoolean && passwordMismatchBoolean && validEmail) {
submit.disabled = false;
}
}
<div id="error-display"></div>
<br>
<form id="project-form" action="/submit.php" method="get" onclick="formValidation()">
<label>Username:</label>
<input id="username" type="text" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Full Name:</label>
<input id="name" type="text" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Phone Number:</label>
<input id="phone-number" type="tel">
<br>
<label>Email:</label>
<input id="email" type="email" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Password:</label>
<input id="password" type="password" required onblur="formValidation()">
<c>*</c>
<br>
<label>Confirm Password:</label>
<input id="password-confirmation" type="password" required onblur="formValidation()">
<c>*</c>
<br>
<br>
<input id="submit-btn" type="submit" value="Submit" disabled>
</form>
Thanks a lot in advance, and again sorry if i'm breaking the rules.
I would put all the inputs into an object instead, that way you could automatically iterate over the object.
const fieldValues = [
'username',
'name',
'phone-number',
'email',
'password',
'password-confirmation',
]
.reduce((fieldsSoFar, fieldName) => {
fieldsSoFar[fieldName] = document.getElementById(fieldName).value;
return fieldsSoFar;
}, {});
const missingFieldsStr =
Object.entries(fieldValues)
.filter(([, fieldValue]) => fieldValue.length === 0)
.map(([fieldName]) => {
const words = fieldName.split(' ');
const upperWords = words.map(word => word.slice(0, 1).toUpperCase() + word.slice(1))
return upperWords;
})
.join(', ');
if (missingFieldsStr) {
// display it
}
// skipping some lines...
const hasUpper = /[A-Z]/.test(fieldValues.password);
const hasNumber = /[0-9]/.test(fieldValues.password);
And so on.
Don't implicitly create global variables - strongly consider using a linter.
Only use innerHTML when you're deliberately using or inserting HTML markup (which can have security and encoding problems). When you're setting or retrieving text values, use textContent instead.

How to disable "Save" until fields have passed validation. NO <form> tags

On the client-side, I would like to somehow disable the "Save" button in case the validation has not passed. The solution is validating individual fields like so:
//checking if null
$("#editAccountName").blur(function () {
var editAccountName = $("#editAccountName").val();
if (editAccountName == "" || editAccountName == null) {
$("#editAccountNameError").html('<font color="#cc0000">The account name is required</font>');
$("#editAccountName").css("background-color", "#cc0000");
}
else {
$("#editAccountNameError").html('<font color="#cc0000"></font>');
$("#editAccountName").css("background-color", "transparent");
}
});
//checking if null
$("#editAddress").blur(function () {
var editaddress = $("#editAddress").val();
if (editaddress == "" || editaddress == null) {
$("#editAddressError").html('<font color="#cc0000">The address is required</font>');
$("#editAddress").css("background-color", "#cc0000");
}
else {
$("#editAddressError").html('<font color="#cc0000"></font>');
$("#editAddress").css("background-color", "transparent");
}
});
//checking if null
$("#editCity").blur(function () {
var editCity = $("#editCity").val();
if (editCity == "" || editCity == null) {
$("#editCityError").html('<font color="#cc0000">The city is required</font>');
$("#editCity").css("background-color", "#cc0000");
}
else {
$("#editCityError").html('<font color="#cc0000"></font>');
$("#editCity").css("background-color", "transparent");
}
});
//checking if null
$("#editState").blur(function () {
var editState = $("#editState").val();
if (editState == "" || editState == null) {
$("#editStateError").html('<font color="#cc0000">The city is required</font>');
$("#editState").css("background-color", "#cc0000");
}
else {
$("#editStateError").html('<font color="#cc0000"></font>');
$("#editState").css("background-color", "transparent");
}
});
//no nulls or letters
$("#editZip").blur(function () {
var regexnumbers = /\d+-?/;
var editzip = $("#editZip").val();
if (!regexnumbers.test(editzip) == true || editzip == '' || editzip == null) {
$("#editZipError").html('<font color="#cc0000">The numeric zip code is required</font>');
$("#editZip").css("background-color", "#cc0000");
}
else {
$("#editZipError").html('<font color="#cc0000"></font>');
$("#editZip").css("background-color", "transparent");
}
});
//*optional*
//needs to be exactly 10 digits in case anything is entered in any of the boxes
$("#editArea,#editPrefix,#editSuffix").blur(function () {
var phone = $("#editArea").val() + $("#editSuffix").val() + $("#editPrefix").val();
if (phone.length > 0 && phone.length < 10) {
$("#editPhoneError").html('<font color="#cc0000">The phone number must be 10 digits</font>');
$("#editArea").css("background-color", "#cc0000");
$("#editPrefix").css("background-color", "#cc0000");
$("#editSuffix").css("background-color", "#cc0000");
}
else {
$("#editPhoneError").html('<font color="#cc0000"></font>');
$("#editArea").css("background-color", "transparent");
$("#editPrefix").css("background-color", "transparent");
$("#editSuffix").css("background-color", "transparent");
}
});
I know this is not the cleanest solution but I can't make use of the Jquery plugin since that requires me to place the fields between <form> tags (which conflicts with other functionality). The markup looks like this:
<label>Clinic Name</label>
<input id="editAccountName" name="editAccountName" class="accountEdit" type="text" value="#Model.Pharmacy.AccountName" /><span id="editAccountNameError" value="0"></span>
<label>Address</label>
<input id="editAddress" name="editAddress" class="accountEdit" type="text" value="#Model.Pharmacy.Address" /><span id="editAddressError" value="0"></span>
<label>City</label>
<input id="editCity" name="editCity" class="accountEdit" type="text" value="#Model.Pharmacy.City" /><span id="editCityError" value="0"></span>
<label>State</label>
<input id="editState" name="editState" class="accountEdit" type="text" value="#Model.Pharmacy.State" maxlength="2"/><span id="editStateError" value="0"></span>
<label>Zip</label>
<input id="editZip" name="editZip" maxlength="5" class="accountEdit" type="text" value="#Model.Pharmacy.ZipCode" /><span id="editZipError" value="0"></span>
<label>Phone Number (optional)</label>
<div>
<input id="editArea" maxlength="3" onkeyup="tabout(this,'editPrefix')" name="editArea" style="float:left; width:70px;" type="text" value="#Model.Pharmacy.Area" depends />
</div>
<div>
<input id="editPrefix" maxlength="3" onkeyup="tabout(this,'editSuffix')" name="editPrefix" style="float:left; width:70px;" type="text" value="#Model.Pharmacy.Prefix" depends />
</div>
<div>
<input id="editSuffix" maxlength="4" onkeyup="tabout(this,'editPrefix')" name="editSuffix" style="float:left; width:70px;" type="text" value="#Model.Pharmacy.Suffix" depends />
</div>
<span style="margin-left:-208px; margin-top:50px;" id="editPhoneError" value="0"></span>
</div>
<input id="btnCancel" type="button" value="Cancel" />
<input id="btnSave" type="button" value="Save" />
Any suggestions?
So first, instead of setting the background-color on each field when it fails validation, I'd use a special css class - like "error" - that itself defines the look of each field. Then something like this:
if (editaddress == "" || editaddress == null) {
$("#editAddressError").html('<font color="#cc0000">The address is required</font>');
$("#editAddress").css("background-color", "#cc0000");
}
else {
$("#editAddressError").html('<font color="#cc0000"></font>');
$("#editAddress").css("background-color", "transparent");
}
becomes this:
if (editaddress == "" || editaddress == null) {
$("#editAddressError").html('<font color="#cc0000">The address is required</font>');
$("#editAddress").addClass("error");
}
else {
$("#editAddressError").html('<font color="#cc0000"></font>');
$("#editAddress").removeClass("error");
}
(Note that I'd use something similar for the field error spans, but I'll eave that up to you)
Then, you could use the presence of that class ("error") at the end of your validation to enable/disable the save button:
$("#btnSave").prop("disabled", ($(":input.error").length > 0));
Basically, if there's at least one input field with the class "error", disable the save button. Otherwise, enable it.
Hope this helps!
This is a little crazy, but in basic terms you could keep a boolean for each validation rule like so:
$("#editAccountName").blur(function () {
var editAccountName = $("#editAccountName").val();
if (editAccountName == "" || editAccountName == null) {
$("#editAccountNameError").html('<font color="#cc0000">The account name is required</font>');
$("#editAccountName").css("background-color", "#cc0000");
accountNameValid = false;
}
else {
$("#editAccountNameError").html('<font color="#cc0000"></font>');
$("#editAccountName").css("background-color", "transparent");
accountNameValid = true;
}
});
And later check if the button should be clickable:
if(accountNameValid && addressValid && ...){
// process form
}

Try to validate IP Address with javascript

I'm a beginner to javascript. Now, I'm trying to make a form to post back to server. There are some "input" that contains ip address which should be validate before submitting. Now I have done a javascript function which work well. But now I'm trying to add this function into jquery selection. Just confuse how to do it.
This is my validate javascript code.
function ValidateIPaddress(Ipfield)
{
IpAddr=Ipfield.value;
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if(!IpAddr.match(ipformat))
return true;
else
return false;
}
and this is now how I implement for this validation.
<input type= "text" name= "LocalIP" style= "margin-right:10px " value="192.168.1.193" class="ip" onfocusout="ValidateIPaddress(document.getElementById('LocalIp'))" id="LocalIp" > Remote VIP Address :
<input type= "text" name= "RemoteVIPAddr" style= "margin-right:10px" value="234.5.6.7" class="ip" onfocusout="ValidateIPaddress(document.getElementById('RemoteIp'))" id="RemoteIp" >
Remote VIP Port :
<input type= "text" name= "RemoteVIPPort" style= "margin-right:10px" value="5004" class="ip" onfocusout="ValidatePort(document.getElementById('RemoteVIPPort'))" id="RemoteVIPPort">
Now I want to use jquery selection to always check if there are some invalid input. Which is something like this but with my own design function.
$("input.ip:visible").filter(function() { return this.ValidateIPaddress === true }).addClass("invalid");
Anyone has idea bout it?
You're not calling ValidateIPAddress in your filter function, you're just testing whether the DOM element has a non-empty property named ValidateIPAddress. It should be:
$("input.ip:visible").filter(function() {
return ValidateIPAddress(this);
}).addClass("invalid");
Try this:
isIP(ip) {
if (typeof(ip) !== 'string')
return false;
if (!ip.match(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)) {
return false;
}
return ip.split('.').filter(octect => octect >= 0 && octect <= 255).length === 4;
}
Original: https://stackoverflow.com/a/50612630/3261332
And if one needs to accept also CIDR format IP/{0-32} please update the 2 lines as below:
if (!ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(\/([0-9]|[12][0-9]|3[0-2]))?$/)) {
return ip.split('/')[0].split('.').filter(octet => octet >= 0 && octet <= 255).length === 4;
See if this help. This is valid fo IP4 only.
0.0.0.0 - Invalid
Any ip with CIDR is invalid
function validateIP(ip) {
is_valid = false;
ip = ip.replace(/\s+/, "");
if(ip.indexOf('/')!=-1){
alert("IP not valid");
return false
}
try {
var ipb = ip.split('.');
if (ipb.length == 4) {
for (i = 0; i < ipb.length; i++) {
b = parseInt(ipb[i]);
if (b >= 0 && b <= 255) {
is_valid = true;
} else {
is_valid = false;
break;
}
}
}
} catch (exception) {
alert("IP is not valid")
return false;
}
if (!is_valid) {
alert("IP is not valid")
return false;
}
return true;
}

How to do simple client-side form validation using JavaScript/jQuery?

I was doing a project series on CodeCademy and I got a project in the series to do a client side form validation using JavaScript/jQuery.
My HTML is:
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<link rel='stylesheet' href='stylesheet.css' type='text/css'/>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<form>
First Name : <input type='text' id='fname' placeholder='Enter First Name'><br><br>
Last Name : <input type='text' id='lname' placeholder='Enter Last Name'><br><br>
Age : <input type='text' id='age' placeholder='Age'><br><br>
Sex : <input type='radio' class='sex'> Male <input type='radio' class='sex'> Female
</form>
<button id='submit'>Submit</button>
</body>
</html>
My JavaScript/jQuery is:
$(document).ready(function()
{
var fname = document.getElementById('fname').val();
var lname = document.getElementById('lname').val();
var age = document.getElementById('age').val();
/*Do not know how to get element by class and that too, two different type. Have to check if user chose anything or not*/
$("#submit").click(function()
{
if(fname.length === 0)
{
alert("Please input a first name");
}
else if(lname.length === 0)
{
alert("Please input a last name");
}
else if(age.length === 0)
{
alert("Please input an age");
}
});
});
I don't need a very complicated code and please help me in the HTML department if something is wrong there or if something needs to be added there.
Also, I don't know how to get different elements in a class. I have put a comment in my jQuery regarding that so please help if you can.
This is a problem in a CodeCademy project and this is where a lot of newbies in JS and jQuery have a problem, so if you can help, it'll help a lot of people and not just me.
Thanks!
You need to use .value instead of .val() since you're using pure Javascript:
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;
if you want to use .val() method then you need a jQuery object:
var fname = $('#fname').val();
var lname = $('#lname').val();
var age = $('#age').val();
You also need to put those variables inside .click() handler in order to get the updated value of these textboxes, currently you only retrieve the value on page load which is always equal to 0:
$(document).ready(function () {
$("#submit").click(function () {
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;
if (fname.length == 0) {
alert("Please input a first name");
} else if (lname.length == 0) {
alert("Please input a last name");
} else if (age.length == 0) {
alert("Please input an age");
}
});
});
Fiddle Demo
from your example, get elements by class name
var lists = document.getElementsByClassName("sex");
to access specific value use lists[0].value it will return "Male" or lists[1].value will return "Female"
if you use native/pure javascript use .value not val() . val() is only for jquery
It looks like you're asking a couple questions at once.
As suzonraj, pointed out you need document.getElementsByClass to get elements by class name and as Felix pointed out, you need to place your data look up inside your .click event in order to get the current, not page .ready value.
I will add that you should add the name parameter to your radio boxes, so they actually function like radio boxes - turning one off when another is clicked. With this, you could use document.getElementsByName, which is really what you're after with a radio collection.
As far as validation, you would then need to go through your array of elements by name or class, and then validate that at least one is .checked.
Here is an example based off the code Felix shared: http://jsfiddle.net/5zqW7/8/
One addition, is that validation occurs for all elements rather than just until the first element that fails. This is a little more communicative to the user, as it will identify all the wrong fields, not just the first, hit submit, then the second, and so on. In a real form, you'd probably have something less loud than an alert() anyhow. That may not be necessary for your assignment.
Here is very simple way to make form validation using jquery
// Wait for the DOM to be ready
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='registration']").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
firstname: "required",
lastname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 5
}
},
// Specify validation error messages
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: {
required: "Please provide a valid user name",
email: "Please enter a valid email address"
}
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
#import url("https://fonts.googleapis.com/css?family=Open+Sans");
/* Styles */
* {
margin: 0;
padding: 0;
}
body {
font-family: "Open Sans";
font-size: 14px;
}
.container {
width: 500px;
margin: 25px auto;
}
form {
padding: 20px;
background: #2c3e50;
color: #fff;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
form label,
form input,
form button {
border: 0;
margin-bottom: 3px;
display: block;
width: 100%;
}
form input {
height: 25px;
line-height: 25px;
background: #fff;
color: #000;
padding: 0 6px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
form button {
height: 30px;
line-height: 30px;
background: #e67e22;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
label.error {
color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js'></script>
<div class="container">
<h2>Registration</h2>
<form action="" name="registration">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="john#doe.com" />
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="●●●●●" />
<button type="submit">Register</button>
</form>
</div>
function validate() {
var scheduledOn = $("#ScheduledOn").val();
var status = $(".Status option:selected").text();
var result = true;
if (id == "") {
var scheduledOn = $("#ScheduledOn").val();
var category = $(".categoryList option:selected").text();
var activityTask = $(".activityTaskList option:selected").text();
var lead = $("#LeadID").val();
var agent = $("#AgentID").val();
if (category == "Select Category") {
$("#categoryValidation").show();
$("#categoryValidation").text("The Category field is required");
}
else {
$("#categoryValidation").hide();
}
if (category == "Agent Recruitment" || category == "Direct Sales" || category == "Joint Field Work" || category == "Select Category" || category == "Agent Development") {
var activityTask = $(".activityTaskList option:selected").text();
if (activityTask == "Select Activity Task") {
$("#activityTaskValidation").show();
$("#activityTaskValidation").text("The Activity Task field is required");
}
else {
$("#activityTaskValidation").hide();
}
}
if (category == "Joint Field Work") {
if (agent == "" || agent == "Select Agent") {
$("#agentValidation").show();
$("#agentValidation").text("The Agent field is required");
result = false;
}
else {
$("#agentValidation").hide();
}
}
if (category == "Joint Field Work") {
if (lead == "" || lead == null || lead == "Select Lead") {
$("#leadValidation").show();
$("#leadValidation").text("The Lead field is required");
result = false;
}
else {
$("#leadValidation").hide();
}
}
if (category == "Agent Recruitment" || category == "Agent Development") {
if (agent == "" || agent == "Select Agent") {
$("#agentValidation").show();
$("#agentValidation").text("The Agent field is required");
result = false;
}
else {
$("#agentValidation").hide();
}
}
if (category == "Direct Sales") {
if (lead == "" || lead == "Select Lead" || lead == null) {
$("#leadValidation").show();
$("#leadValidation").text("The Lead field is required");
result = false;
}
else {
$("#leadValidation").hide();
}
}
if (scheduledOn == "" || scheduledOn == null) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field is required");
result = false;
}
else if (Date.parse(scheduledOn) <= Date.now()) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
result = false;
}
else {
$("#scheduledOnValidation").hide();
}
return result;
}
else {
var scheduledOn = $("#NewScheduledOn").val();
var status = $(".Status option:selected").text();
if (document.getElementById("SetAppointment_Y").checked) {
var activityTask = $(".activityTaskList").val();
if (activityTask == null || activityTask == "") {
$("#activityTaskValidation").show();
$("#activityTaskValidation").text("The Activity Task field is required");
result = false;
}
else {
$("#activityTaskValidation").hide();
$("#scheduledOnValidation").hide();
}
if (status != null && (scheduledOn == "" || scheduledOn == null)) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field is required");
$("#statusValidation").hide();
result = false;
}
else if (Date.parse(scheduledOn) <= Date.now()) {
$("#scheduledOnValidation").show();
$("#scheduledOnValidation").text("The Scheduled On field should be greater than current date time");
result = false;
}
else {
$("#scheduledOnValidation").hide();
$("#statusValidation").show();
}
}
}
return result;
}

Categories

Resources