I have a student form with some input fields.Details like Name , Age should be entered.If the age of the student is less than 18 , parent details needs to be entered mandatory.
So in this case , i am checking the age of the student .If the age is less than 18 , i will shifting the focus to the parent text field.
The real trick here is i don't want the field to be empty.So until a value is entered ,the focus should be on the parent text field and cannot be changed.
How to achieve this ?
<label for="name">Name</label>
<input id="name" type="text" name="name" />
<label for="age">Age</label>
<input id="age" type="text" name="age" onblur="myFunction()"/>
<label for="parent">Parent</label>
<input id="parent" type="text" name="parent" />
JSFIDDLE
Any suggestions and ideas are welcome..
You are looking for something like this:
var x = document.getElementById("age").value;
if (x < 18)
{
if (document.getElementById("parent").value == "")
{
alert('Parent detail is mandatory');
document.getElementById('parent').focus();
return;
}
}
JSFIDDLE
check this fiddle
I hope this is what you are looking for,
<label for="name">Name</label>
<input id="name" type="text" name="name" onblur="checkage()" />
<label for="age">Age</label>
<input id="age" type="text" name="age" onblur="myFunction()"/>
<label for="parent">parent</label>
<input id="parent" type="text" name="parent" />
var age;
function myFunction() {
age = document.getElementById("age").value;
if(age < 18)
document.getElementById('parent').focus();
}
function checkage(){
var parent = document.getElementById('parent').value;
if(age < 18 && parent == '')
document.getElementById('parent').focus();
}
Here is a possible solution: https://jsfiddle.net/gwcgrn1s/1/
<label for="name">Name</label>
<input id="name" type="text" name="name" />
<label for="age">Age</label>
<input id="age" type="text" name="age" onblur="myFunction()"/>
<label for="parent">parent</label>
<input id="parent" type="text" name="parent" onblur="ValidationFunction()" />
function myFunction() {
var x = document.getElementById("age").value;
if (x <18)
{
document.getElementById("parent").focus();
}
}
function ValidationFunction()
{
var parentName = document.getElementById("parent").value.trim();
if (parentName.length == 0)
{
document.getElementById("parent").focus();
}
}
Related
<form action="#"></form>
<label for="First-name">First name: </label>
<input type="text" id="First-name" placeholder="Please insert fiid."><br>
<label for="Second-name">Second name: </label>
<input type="text" id="Second-name" placeholder="Please insert second name"> <br>
<label for="Passenger-weight">Passengers weight: </label>
<input type="number" class="weight" id ="Passenger-weight" placeholder="Please enter passengers weight"><br>
<label for="cargo-weight">cargo weight: </label>
<input type="number" class="weight" id ="cargo-weight" placeholder="Please enter cargo weight"><br>
<input type="submit" id ="submit" ><br>
</form>
<p id="sum"></p>
<div id="sumoftotal"></div>
<body>
<script language="JavaScript">
document.getElementById("submit").onclick=function (){
let firstName = document.getElementById("First-name").value;
let lastName= document.getElementById("Second-name").value;
let num1 = document.getElementById("Passenger-weight").value;
let num2 = document.getElementById("cargo-weight").value;
let total =parseInt(num1) + parseInt(num2);
document.getElementById("sum").innerHTML=(`${firstName} ${lastName} ${total }`)
}
</script>
</body>
my problem can be numbered:
number 1: when I press the submit button, input values show up, BUT when I want to insert a different data, the previous one disappear. I studied about it, because whatever comes in the function scope become local we cannot apply it outside, BUT I don't know how to change it.
number 2: I want to have the sum of total weights I insert at the end of my list, I know we can do this by loop, BUT I need something simpler and more preliminary because I am a novice and it would be a big jump for the time being.
all in all, I would be happy if anyone could help me.
Here is the primary and most basic approach.
var data = document.getElementById('data');
var weightElement = document.getElementById('total-weight');
document.getElementById("submit").onclick = function() {
/* Getting data */
let firstName = document.getElementById("First-name").value;
let lastName = document.getElementById("Second-name").value;
let num1 = document.getElementById("Passenger-weight").value;
let num2 = document.getElementById("cargo-weight").value;
let total = parseInt(num1) + parseInt(num2);
/* Appending element */
data.innerHTML = data.innerHTML + `First Name - ${firstName}, Last Name - ${lastName}, Weight - ${total} <br/>`;
weightElement.innerHTML = parseInt(weightElement.innerHTML) + total;
}
<body>
<form action="#"></form>
<label for="First-name">First name: </label>
<input type="text" id="First-name" placeholder="Please insert fiid."><br>
<label for="Second-name">Second name: </label>
<input type="text" id="Second-name" placeholder="Please insert second name"> <br>
<label for="Passenger-weight">Passengers weight: </label>
<input type="number" class="weight" id="Passenger-weight" placeholder="Please enter passengers weight"><br>
<label for="cargo-weight">cargo weight: </label>
<input type="number" class="weight" id="cargo-weight" placeholder="Please enter cargo weight"><br>
<input type="submit" id="submit"><br>
</form>
<div id="data"></div>
<div>Total weight = <span id="total-weight">0</span></div>
</body>
How to save all the values from customer? I can only save first name and last name. Can I pass more than 2 inputs in set details? I tried adding date of birth that had input type text in dd/mm/yyyy format but the value was being shown as "undefined".
Java Script
function getDetails(){
if (typeof(Storage)!=="undefined"){
if (sessionStorage.getItem("firstName") !== null){
document.getElementById("firstName").value = sessionStorage.getItem("firstName");
}
if (sessionStorage.getItem("lastName") !== null){
document.getElementById("lastName").value = sessionStorage.getItem("lastName");
}
}
}
function setDetails(firstName, lastName) {
if (typeof(Storage)!=="undefined"){
sessionStorage.setItem("firstName", firstName);
sessionStorage.setItem("lastName", lastName);
}
}
HTML Code
<label for="firstName">First Name</label>
<br>
<input type="text" name="firstName" id="firstName" placeholder= "Enter first name" title="20 characters" />
<br>
<label for="lastName">Last Name</label>
<br>
<input type="text" name="lastName" id="lastName" placeholder= "Enter last name" class="field" required pattern="([A-z]){1,20}" title="20 characters" />
<br>
<label for="dob">Date of Birth</label>
<br>
<input type="text" name="dob" id="dob" maxlength="10" placeholder="dd/mm/yyyy" pattern="\d{1,2}\/\d{1,2}\/\d{4}"/>
Below code will work to set & get "dob" in cookie:
<html>
<body>
<label for="dob">Date of Birth</label>
<br>
<input type="text" name="dob" id="dob" maxlength="10" placeholder="dd/mm/yyyy" pattern="\d{1,2}\/\d{1,2}\/\d{4}"/>
<button onclick = "setDateInCookie();">SetCookie</button>
<button onclick = "getDateFromCookie();">GetCookie</button>
<script>
function setDateInCookie(){
var myDate = document.getElementById("dob").value;
if(typeof(Storage)!=="undefined")
sessionStorage["myDate"] = myDate;
}
function getDateFromCookie(){
var myDate = document.getElementById("dob").value;
if(typeof(Storage)!=="undefined")
{
if (sessionStorage.getItem("myDate") !== null){
document.getElementById("dob").value = sessionStorage.getItem("myDate");
}
}
}
</script>
</body>
</html>
Future Note: Avoid using input type "text" for input type "date". Use the exact input types for not getting any issues in future.
If any of the form validations do not match, it is supposed to add one to a counter. At the end, if the counter is greater than zero, it is supposed to return false and not allow the form to submit.
I've written the code in Brackets. I've tried using both a hosted site and live preview to test the code, both of which result in the same issue. I've tried turning the function into a variable. I've tried different methods of taking the variables from the form. I've tried simply copying a different solution I found to this through google. Nothing seems to be working to get the validation to work as intended.
I apologize ahead of time for the wall of code.
JavaScript:
function checkAll(){
var userNameVerification = "0-9a-zA-Z"; //must include upper and lowercase so that user may use caps
var phoneNumberVerification = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; //taken from w3resoucre for the setup of phone number verification
var checker = 0;
var userName = document.regForm.userName.value;
var password = document.regForm.passwordvalue;
var passwordVerify = document.regForm.passwordVerify.value;
var firstName = document.regForm.firstName.value;
var lastName = document.regForm.lastName.value;
var email = document.regForm.email.value;
var phoneNumber = document.regForm.phoneNumber.value;
var signUpNewsletter = document.regForm.phoneNumber.value;
//check if username is empty
if(userName == ""){
document.getElementById('errorUserName').innerHTML = "Username cannot be empty.";
checker++;
}
//make sure username uses proper characters
if(!userName.match(userNameVerification)){
document.getElementById('errorUserName').innerHTLM = "Enter only numbers and letters.";
checker++;
}
//check if password is empty or is shorter than 8 characters
if(password == "" || password.lenth < 8) {
document.getElementById('errorPassword').innerHTML = "Password should be at least 8 characters long.";
checker++;
}
//make sure confirmation of password is not shorter than 8 and is not empty
if(passwordVerify == "" || passwordVerify.lenth < 8) {
document.getElementById('errorPasswordVerify').innerHTML = "Confirmation Password should be at least 8 characters long.";
checker++;
}
//passwords match
if(password != passwordVerify){
document.getElementById('errorPasswordVerify').innerHTML = "Passwords do not match.";
checker++;
}
//check if first name is empty
if(firstName == ""){
document.getElementById('errorFirstName').innerHTML = "First name cannot be empty.";
checker++;
}
//check if last name is empty
if(lastName == ""){
document.getElementById('errorLastName').innerHTML = "Last Name cannot be empty.";
checker++;
}
//check if email is empty
if(email == ""){
document.getElementById('errorEmail').innerHTML = "Email cannot be empty.";
checker++;
}
//check that # and . are present
if(email.indexOf("#",0) < 0 || email.indexOf(".",0) < 0){
document.getElementById('errorEmail').innerHTML = "Enter a valid email address.";
checker++;
}
//check if phone number is empty
if(phoneNumber == ""){
document.getElementById('errorPhoneNumber').innerHTML = "You must enter a phone number.";
checker++;
}
//make sure phone number is in proper format
if(!phoneNumber.match(phoneNumberVerification)){
document.getElementById('errorPhoneNumber').innerHTML = "Enter a valid phone number in (XXX)XXX-XXXX format.";
checker++;
}
//make sure one of the radio buttons are clicked
if((signUpNewsletter[0].checked == false) && (signUpNewsletter[1].checked == false)){
document.getElementById('errorSignUp').innerHTML = "Please select one of the options.";
checker++;
}
//see if checker is greater than 0; if so, return false
if(checker > 0){
return false;
}
}
HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Invitation Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script type="text/javascript" src="js/registration.js"></script>
</head>
<body>
<header>
<div class="top">
<a class="logo" href="index.html">CapellaVolunteers<span class="dotcom">.org</span></a>
</div>
<nav>
<ul class="topnav">
<li>Home
</li>
<li>Invitation
</li>
<li>Volunteers
</li>
<li>Gallery
</li>
<li>Registration
</li>
</ul>
</nav>
</header>
<section id="pageForm">
<form name="regForm" action="confirmation.php" method="POST">
<label for="userName">Username:</label>
<input type="text" name="userName" placeholder="Enter your Username" />
<span id="errorUserName"></span><br>
<label for="Password">Password:
</label>
<input type="password" name="password" placeholder="Enter your Password" />
<span id="errorPassword"></span><br>
<label for="passwordVerify">Verify your Password:
</label>
<input type="password" name="passwordVerify" placeholder="Enter in your Password again" />
<span id="errorPasswordVerify"></span><br>
<label for="firstName">First Name:
</label>
<input type="text" name="firstName" placeholder="Enter your First Name" />
<span id="errorFirstName"></span><br>
<label for="lastName">Last Name:
</label>
<input type="text" name="lastName" placeholder="Enter your Last Name" />
<span id="errorLastName"></span><br>
<label for="email">Email:
</label>
<input type="text" name="email" placeholder="Enter your Email Address" />
<span id="errorEmail"></span><br>
<label for="phoneNumber">Phone Number
</label>
<input type="text" name="lastName" placeholder="Enter your Phone Number" />
<span id="errorPhoneNumber"></span><br>
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" value="Yes" checked> Yes
<input type="radio" name="signUpNewsletter" value="No"> No
<span id="errorSignUp"></span><br>
<input type="submit" value="Next step" onsubmit="return checkAll();">
</form>
</section>
<footer>This events site is for IT3515 tasks.
</footer>
</body>
</html>
I expect the form to not submit when the information is not validated (for example, I try submitting an empty form, which it should not allow me to do), but it actually submits the form no matter what information is inserted into the form.
Add your onsubmit call to form instead of button, it works. Don't know about your logic, but it works. Run this code!
function checkAll(){
var condition = false;
if(condition){
alert ('All ok');
return true;
}
alert('Something wrong');
return false;
}
<section id="pageForm">
<form name="regForm" action="confirmation.php" method="POST" onsubmit="return checkAll();">
<label for="userName">Username:</label>
<input type="text" name="userName" placeholder="Enter your Username" />
<span id="errorUserName"></span><br>
<label for="Password">Password:
</label>
<input type="password" name="password" placeholder="Enter your Password" />
<span id="errorPassword"></span><br>
<label for="passwordVerify">Verify your Password:
</label>
<input type="password" name="passwordVerify" placeholder="Enter in your Password again" />
<span id="errorPasswordVerify"></span><br>
<label for="firstName">First Name:
</label>
<input type="text" name="firstName" placeholder="Enter your First Name" />
<span id="errorFirstName"></span><br>
<label for="lastName">Last Name:
</label>
<input type="text" name="lastName" placeholder="Enter your Last Name" />
<span id="errorLastName"></span><br>
<label for="email">Email:
</label>
<input type="text" name="email" placeholder="Enter your Email Address" />
<span id="errorEmail"></span><br>
<label for="phoneNumber">Phone Number
</label>
<input type="text" name="lastName" placeholder="Enter your Phone Number" />
<span id="errorPhoneNumber"></span><br>
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" value="Yes" checked> Yes
<input type="radio" name="signUpNewsletter" value="No"> No
<span id="errorSignUp"></span><br>
<input type="submit" value="Next step" >
</form>
</section>
for a class project I have to build a website for a pet store, featuring a pet grooming service. This involves a form, php and a mysql server on my localhost. I have been unable to correctly validate this form via a jQuery validator plugin for some unknown (to me) reason.
I've had no luck via regular jQuery code beyond getting the form to not submit blank input values. So as it is, anybody can put 'sadklfhsdk' in any of the fields (except for email, unless it has a '#') and it will validate and submit to the server.
So after I going through a couple of tutorials this is what I have so far:
The HTML:
<body>
<div id="h2Groom"><h2>Grooming Request Form</h2></div>
<form id="groom_form" method="post" action="insertPS.php">
<div id="result"></div>
<label for="firstName"><span>First Name:</span>
<input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name" class="required"/>
</label>
<label for="lastName"><span>Last Name:</span>
<input type="text" name="lastName" id="lastName" placeholder="Enter Your Last Name" class="required"/>
</label>
<label for="email"><span>Email Address:</span>
<span id="error"></span>
<input type="email" name="email" id="email" placeholder="Enter a Email"/>
</label>
<label for="phone"><span>Phone Number:</span>
<span id="error"></span>
<input type="text" name="phone" id="phone" placeholder="Enter a phone number" class="required"/>
</label>
<label for="address"><span>Address:</span>
<input type="text" name="address" id="address" placeholder="Enter your address" class="required"/>
</label>
<label for="city"><span>City:</span>
<input type="text" name="city" id="city" placeholder="Enter your city" />
</label>
<label for="state"><span>State:</span>
<input type="text" name="state" id="state" placeholder="Enter your state" class="required"/>
</label>
<label for="zipcode"><span>Zipcode:</span>
<input type="text" name="zipcode" id="zipcode" placeholder="Enter your zipcode" class="required"/>
</label>
<label for="petType"><span>Type of Pet:</span>
<ul>
<li><label><input name="petType" type="radio" value="dog" id="dog">Dog</label></li>
<li><label><input name="petType" type="radio" value="cat" id="cat">Cat</label></li>
<li><label><input name="petType" type="radio" value="bird" id="bird">Bird</label></li>
</ul>
</label>
<select id="breed" name="breed">
<option value="0">--Please Choose Dog Breed--</option>
<option value="AlaskanMal">Alaskan Malamute</option>
<option value="Bichon">Bichon Frise</option>
<option value="WelshCorgi">Corgi, Welsh</option>
<option value="Dalmation">Dalmation</option>
<option value="EnglishToySpan">English Toy Spaniel</option>
<option value="FrenchBull">French Bull Dog</option>
<option value="Greyhound">Greyhound</option>
<option value="Papillon">Papillon</option>
<option value="Rottweiler">Rottweiler</option>
<option value="YorkshireTerr">Yorkshire Terrier</option>
</select>
<label for="neut"><span>Check box if your pet has been neutered/spayed (leave unchecked if not).</span></label>
<ul>
<label>
<li><input type="checkbox" name="neut" id="neut" />Yes</li></label>
</ul>
<br />
<br />
<br />
<label for="petname"><span>Pet Name:</span>
<input type="text" name="petname" id="petname" placeholder="Enter your pet's name" class="required" />
</label>
<label for="petBday"><span>Pet's Birthday:</span>
<input type="date" id="petBday" name="petBday"/>
</label>
<span> </span>
<input type="submit" id="submitBttn" value="Submit" /><input type="reset" id="resetBttn" value="Reset" />
</form>
</body>
The jQUERY (except the script to send values to server, see jsfiddle link):
$(document).ready(function() {
$('input[name=petType]').click(function() {
if(this.id=='dog') {
$('#breed').show('slow');
}
else {
$('#breed').hide('slow');
}
});
$('input[name=phone]').blur(function() {
if (validatePhone('phone')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$('input[name=email]').blur(function() {
if (validateEmail('email')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$("#submitBttn").click(function() {
//get input field values
var user_firstName = $('input[name=firstName]').val();
var user_lastName = $('input[name=lastName]').val();
var user_email = $('input[name=email]').val();
var user_address = $('input[name=address]').val();
var user_phone = $('input[name=phone]').val();
var user_city = $('input[name=city]').val();
var user_state = $('input[name=state]').val();
var user_zipcode = $('input[name=zipcode]').val();
var user_petname = $('input[name=petname]').val();
var checked_radio = $('input:radio[name=petType]').is(':checked');
var user_neut = $('input:checkbox[name=neut]').is(':checked');
var user_breed = $('input:select[name=breed]').is(':selected');
var txtVal = $('#petBday').val();
if(isDate(txtVal))
alert('Valid Date');
else
alert('Invalid Date');
var proceed = true;
//Validation functions, executed when user hits "submit"
function validatePhone(phone) {
var a = document.getElementById(phone).value;
var filter = /^[0-9-+]+$/;
if (filter.text(phone)) {
return true;
}
else {
return false;
}
}
function validateEmail(email) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(email)) {
return true;
}
else {
return false;
}
}
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
//declare regex
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var dtArray = currVal.match(rxDatePattern); //is the format ok?
if(dtArray ==null)
return false;
//checks for mm/dd/yyyy format
dtMonth = dtArray[1];
dtDay = dtArray[3];
dtYear = dtArray[5];
if(dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay > 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if(dtDay > 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
EDIT: corrected if(filter.text()) to if(filter.test(phone)). None of my java validation code works.
validatePhone: filter.text should be spelled test
<pre>
<script>
// here i want to check form validation
//if i use for loop txtbox2 is not exist in my form so i am getting Js error
//Don't write individual validation
//check element is exist or not if exist check for validation
//I need know how to check an element is exist or not
</script>
<form
<input type="text" id="txtbox1" name="txtbox1" />*
<input type="text" id="txtbox3" name="txtbox3" />*
<input type="text" id="txtbox4" name="txtbox4" />*
<input type="text" id="txtbox5" name="txtbox5" />*
<input type="text" id="txtbox15" name="txtbox15" />*
<input type="text" id="txtbox28" name="txtbox28" />*
</pre>
Apply a class to them:
<input type="text" id="txtbox1" name="txtbox1" class="txt" />
<input type="text" id="txtbox3" name="txtbox3" class="txt" />
<input type="text" id="txtbox4" name="txtbox4" class="txt" />
<input type="text" id="txtbox5" name="txtbox5" class="txt" />
<input type="text" id="txtbox15" name="txtbox15" class="txt" />
<input type="text" id="txtbox28" name="txtbox28" class="txt" />
and go about like this:
function validate(){
var elms = document.getElementsByTagName('input');
for (var i = 0; i < elms.length; i++){
if (elms[i].className === 'txt'){
if (elms[i].value === ''){
alert('Make sure to fill in all required fields');
// now focus it
elms[i].focus();
return false;
}
}
}
return true;
}
And then call the above function like this:
<form ............ onsubmit="return validate();">
Post your code.
Easiest way to validate is by using jquery validate plugin.(Why write your own code when somebody else has done the same?).
An example
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#feedbackform").validate();
});
</script>
<body>
<form id = "feedbackform" method = "POST" action = "">
<h3><span>Contact Us</span></h3>
<fieldset>
<legend>Contact form</legend>
<label for="id_name">Name *</label>
<input id="id_name" class="required" type="text" name="name" />
<label for="id_email">Email</label>
<input id="id_email" type="email" name="email" class="email"/>
<label for="id_comments">Message *</label>
<textarea id="id_comments" class="required" name="comments"></textarea>
<button type="submit">Send</button>
</fieldset>
</form>
The elements that you want to validate add class="required". I hope the example provided is self-explainatory
You can get a reference to the element and check if the reference is null or not:
for (var i=1; i<=100; i++) {
var elem = document.getElementById('txtbox' + i);
if (elem != null) {
...
}
}
Another approach is to look at the elements in the form, but then you need a way to access the form of course:
var elems = document.getElementById('IdOfTheForm').elements;
for (var i=0; i<elems.length; i++) {
var elem = elems[i];
if (elem.tagName == 'INPUT' && elem.type == 'text' && elem.id.length > 6 && elemt.id.substr(0,6) == 'txtbox') {
...
}
}