I am trying to figure out what is the problem with the form. It just opens the file "form.hmtl" and gives me an error.
<!DOCTYPE html>
<html lang="en-US" class="Html" id="Main" dir="auto">
<head class="Head" id="Main">
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="description" content="NRN">
<meta name="author" content="NRN">
<title class="Title" id="Title">NRN</title>
</head>
<body class="Body" id="Main">
<script type="text/javascript">
function checkForm(form)
{
var x = document.getElementById("name");
x.value = x.value.toUpperCase();
var y = document.getElementById("number");
y.value = y.value.split(-,4);
var z = document.getElementById("three");
var i = document.getElementById("four");
var alph = /^[\w ]+$/;
var cardnumb = /^\d{4}-\d{4}-\d{4}-\d{4}$/;
var cvvnumb = /^\d{3}$/;
var monthnumb = /^\d{1,2}$/;
var yearnumb = /^\d{4}$/;
var errors=[];
if(form.one.value == "") {
errors.push("Please enter your full name!");
}
else if(!alph.test(form.one.value)) {
errors.push("Full name is wrong or includes invalid characters!");
if(form.two.value == "") {
errors.push("Please enter your 16-digit code!");
}
else if(!cardnumb.test(form.two.value)) {
errors.push("Card number does not consist of 16 digits or includes invalid characters!");
if(form.three.value == "") {
errors.push("Please enter your month of expiration!");
}
else if(!monthnumb.test(form.three.value)) {
errors.push("The month does not consist of 2 digits or includes invalid characters!");
if Number(z.value) > 12 {
errors.push("The month must be between (0)1 or 12!");
}
if(form.four.value == "") {
errors.push("Please enter your year of expiration!");
}
else if(!yearnumb.test(form.four.value)) {
errors.push("The year does not consist of 4 digits or includes invalid characters!");
if Number(i.value) < 2017 {
errors.push("The year must be greather than 2017!");
}
if(form.five.value == "") {
errors.push("Please enter your 3-digit CVV code!");
}
else if(!cvvnumb.test(form.five.value)) {
errors.push("The CVV does not consist of 3 digits or includes invalid characters!");
if (errors.lenght > 0) {
var msg = "Errors: \n\n";
for (var i=0; i<errors.lenght; i++) {
msg += errors[i] + "\n";
}
alert(msg);
return false;
}
return true;
}
</script>
<nav>
<ul>
<li>Home</li>
</ul>
</nav>
<p class="p1">Payment form validation using JavaScript<p>
<form method="post" action="form.html" onsubmit="return checkForm(this);">
<div class="form-group-name">
<label for="name">Owner</label><br>
<input type="text" placeholder="Name on card" class="form-control-1" id="name" name="one">
</div>
<div class="form-group-number">
<label for="number">Card number</label><br>
<input type="text" placeholder="16-digit code" class="form-control-2" id="number" name="two">
</div>
<div class="form-group-date">
<label for="date">Expiration date</label><br>
<input type="text" placeholder="Month" class="form-control-3" id="date" name="three">
<input type="text" placeholder="Year" class="form-control-3" id="date2" name="four">
</div>
<div class="form-group-cvv">
<label for="cvv">CVV</label><br>
<input type="text" placeholder="3-digit code" class="form-control-4" id="cvv" name="five">
</div>
<div class="form-group-submit">
<input type='submit' class='submit_form' value='Validate'>
</div>
</form>
What can be the problem? Please help me! Thank in advance! Perhaps it is something that is not noticeable.
<script type="text/javascript">
function checkForm(form) {
var x = document.getElementById("name");
x.value = x.value.toUpperCase();
var y = document.getElementById("number");
y.value = y.value.split(-, 4);
var z = document.getElementById("three");
var i = document.getElementById("four");
var alph = /^[\w ]+$/;
var cardnumb = /^\d{4}-\d{4}-\d{4}-\d{4}$/;
var cvvnumb = /^\d{3}$/;
var monthnumb = /^\d{1,2}$/;
var yearnumb = /^\d{4}$/;
var errors = [];
if (form.one.value == "") {
errors.push("Please enter your full name!");
}
else if (!alph.test(form.one.value)) {
errors.push("Full name is wrong or includes invalid characters!");
}
if (form.two.value == "") {
errors.push("Please enter your 16-digit code!");
}
else if (!cardnumb.test(form.two.value)) {
errors.push("Card number does not consist of 16 digits or includes invalid characters!");
}
if (form.three.value == "") {
errors.push("Please enter your month of expiration!");
}
else if (!monthnumb.test(form.three.value)) {
errors.push("The month does not consist of 2 digits or includes invalid characters!");
}
if (Number(z.value) > 12) {
errors.push("The month must be between (0)1 or 12!");
}
if (form.four.value == "") {
errors.push("Please enter your year of expiration!");
}
else if (!yearnumb.test(form.four.value)) {
errors.push("The year does not consist of 4 digits or includes invalid characters!");
}
if (Number(i.value) < 2017) {
errors.push("The year must be greather than 2017!");
}
if (form.five.value == "") {
errors.push("Please enter your 3-digit CVV code!");
}
else if (!cvvnumb.test(form.five.value)) {
errors.push("The CVV does not consist of 3 digits or includes invalid characters!");
}
if (errors.lenght > 0) {
var msg = "Errors: \n\n";
for (var i = 0; i < errors.lenght; i++) {
msg += errors[i] + "\n";
}
alert(msg);
return false;
}
return true;
}
</script>
Change your all js code and try.
Related
I have my javascript file and code done, called script.js and I've added it to my HTML file. I'm very new to this and I'm not sure if I'm doing it right. the functions don't seem to work either. I am very lost and would just like yo figure it out. thank you.
this is my javascript file called (script.js)
$(document).ready(function () {
//When add database, will pull total from database
var total = 30;
var totalTax = total * 0.8;
var totalShip = total * 0.3;
var totalAll = total + totalTax + totalShip;
document.getElementById("totalShop").innerHTML = total;
document.getElementById("totalTax").innerHTML = totalTax;
document.getElementById("shipping").innerHTML = totalShip;
document.getElementById("totalDue").innerHTML = totalAll;
});
function applyActiveCss(id) {
for (var i = 0; i < document.links.length; i++) {
if (document.links[i].id == id) {
document.links[i].className = 'active';
}
else {
document.links[i].className = 'links';
}
}
}
function validateCheckout() {
if (document.checkoutForm.cardNumber.value == "") {
alert("Please provide card number");
document.checkoutForm.cardNumber.focus();
return false;
}
if (document.checkoutForm.month.value == "" || isNaN(document.checkoutForm.month.value) ||
document.checkoutForm.month.value.length != 2) {
alert("Please provide your month");
document.checkoutForm.month.focus();
return false;
}
if (document.checkoutForm.year.value == "" || isNaN(document.checkoutForm.year.value) ||
document.checkoutForm.year.value.length != 4) {
alert("Please provide your month");
document.checkoutForm.year.focus();
return false;
}
return (true);
}
function validateUserInfo() {
if (document.userInfo.fullname.value == "") {
alert("Please provide full name");
document.checkoutForm.cardNumber.focus();
return false;
}
if (document.userInfo.email.value == "") {
alert("Please provide your Email!");
document.userInfo.email.focus();
return false;
}
var emailID = document.userInfo.email.value;
var atpos = emailID.indexOf("#");
var dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || (dotpos - atpos < 2)) {
alert("Please enter correct email ID")
document.userInfo.email.focus();
return false;
}
if (document.userInfo.zipcode.value == "" ||
isNaN(document.userInfo.zipcode.value) ||
document.userInfo.zipcode.value.length != 5) {
alert("Please provide a zip in the format 12345");
document.userInfo.zipcode.focus();
return false;
}
var phoneID = document.userInfo.phone.value;
var dashpos1 = phoneID.indexOf("-");
var dashpos2 = phoneID.lastIndexOf("-");
for (var i = 3; i < 7; i++) {
phoneID[i] = phoneID[i + 1];
}
for (var j = 6; j < 8; j++) {
phoneID[j] = phoneID[j + 2];
}
if (document.userInfo.phone.value == "" ||
document.userInfo.phone.value.length != 12
|| dashpos1 != 3 || dashpos2 != 7 || isNaN(phoneID)) {
alert("Please provide a phone number in the format 123-456-7890");
document.userInfo.phone.focus();
return false;
}
return (true);
}
and this is part of my HTML file called (userinfo.html)
¿<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Personal Information</title>
<link rel="stylesheet" type="text/css" href="StyleSheet1.css">
</head>
<body>
<script src="script.js"> </script>
<h1>User Information</h1>
<p>Please fill out the following information.</p>
<!--<form class="" action="submit.php" method="post">-->
<form action=".shipinfo.html" name="userInfo" onsubmit="return (validateUserInfo());">
<table>
<tbody>
<tr>
<td>
Full Name: <br>
<input type="text" maxlength="100" name="fullname" required>
</td>
<td>
Phone Number: <br>
<input type="number" minlength = "12" maxlength="12" name="phone"
placeholder="123-456-7890">
</td>
</tr>
<tr>
<td>
Address Line 1: <br>
<input type="text" maxlength="100" name="add1" required>
</td>
<td>
Address Line 2: <br>
<input type="text" maxlength="100" name="add2">
</td>
</tr>
<tr>
<td>
City: <br>
<input type="text" maxlength="100" name="city" required>
</td>
I dont see the following jquery script in your file (so it does not read the document ready part and you do not see the 'document loaded' in your console.
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
Another error you are getting in the console is 'Cannot read property 'innerHTML' of null' for this:
document.getElementById("totalShip").innerHTML = total;
This happens when the element, in this case 'totalship', is not accessible or available in your webpage and as such its property cannot be read. Since you are accessing an id, can you provide your css file here?
In addition, where is the access to your database through these files (.userInfo, .checkoutForm etc.) are not accessible via your files as of now.
I want to validate my checkboxes to make sure that the user checked at least one, however I keep getting this error:
Uncaught TypeError: Cannot read property 'checked' of undefined.
Here is part of the HTML:
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required): <input type="text" name="userName" id="userName" required=""><br> E-Mail (Required): <input type="text" name="mail" id="mail" required=""><br> Phone (Required): <input type="text" name="phone" id="phone" required="" onchange="validNumber()"><br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other <br>
<textarea></textarea><br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and part of the JavaScript for the checkboxes:
function validChoice()
{
var bookChoice = document.userSurvey.books.value;
var x= "";
for (i=0;i< 4;i++)
{
if (document.userSurvey['bookChoice'+i].checked)
{
bookChoice = document.userSurvey['bookChoice'+i].value;
x = x +"\n"+ bookChoice;
}
}
if (bookChoice == "")
{
window.alert("You must select at least one book category.");
return false;
}
else
{
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
return true;
}
}
I am currently learning in JavaScript therefore I would prefer help in JavaScript only.
Full Code on JSFiddle:
https://jsfiddle.net/7qh5segc/
You missed some tag names and missspell them in js function:
<h1>User Survey</h1>
<h2><strong>User Information</strong></h2>
<p>Please enter your details below</p>
<br>
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required):
<input type="text" name="userName" id="userName" required="">
<br> E-Mail (Required):
<input type="text" name="email" id="email" required="">
<br> Phone (Required):
<input type="text" name="phone" id="phone" required="" onchange="validNumber()">
<br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other
<br>
<textarea></textarea>
<br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and js code goes like this:
function validName() {
var name = document.userSurvey.userName.value;
if (!/^[a-zA-Z]*$/g.test(name)) {
alert("Please enter letters a - z only");
document.userSurvey.userName.focus();
return false;
} else {
return true;
}
}
function validNumber() {
var theNumbersOnly = "";
var theChar = "";
var theInput = document.userSurvey.phone.value;
for (i = 0; i < theInput.length; i++) {
theChar = theInput.substring(i, i + 1);
if (theChar >= "0" && theChar <= "9") {
theNumbersOnly = "" + theNumbersOnly + theChar;
}
}
if (theNumbersOnly.length < 10) {
alert("You must enter 10 numbers.");
document.userSurvey.phone.focus();
} else {
var areacode = theNumbersOnly.substring(0, 3);
var exchange = theNumbersOnly.substring(3, 6);
var extension = theNumbersOnly.substring(6, 10);
var newNumber = "(" + areacode + ") ";
newNumber += exchange + "-" + extension;
document.userSurvey.phone.value = newNumber;
return true;
}
}
function validEmail() {
var email = document.userSurvey.email.value;
var atLoc = email.indexOf("#", 1);
var dotLoc = email.indexOf(".", atLoc + 2);
var len = email.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc + 2) {
return true;
} else {
alert("Please enter your e-mail address properly.");
return false;
}
}
function validChoice() {
//var bookChoice = document.userSurvey.books.value;
var bookChoice;
var x = "";
for (var i = 0; i < 4; i++) {
if (document.userSurvey.books[i].checked) {
console.log(document.userSurvey);
bookChoice = document.userSurvey.books[i].value;
x = x + "\n" + bookChoice;
}
}
if (bookChoice == "") {
window.alert("You must select at least one book category.");
return false;
} else {
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
console.log(userName);
console.log(eMail);
console.log(phoneNo);
return true;
}
}
function validAll() {
if ((validName() == true) && (validEmail() == true) && (validNumber() == true) && (validChoice() == true)) {
return true;
} else {
return false;
}
}
You missed email tag name too. regards
You can fix the checkbox issue using the following code. A sensible way to get all the checkboxes in this case is using their shared "name" attribute. There are other ways if your structure was different - e.g. using a CSS class, or adding some other custom attribute to the elements.
function validChoice() {
var bookChoices = "";
var checkboxes = document.getElementsByName("books"); //get all elements named "books" into an array
for (i = 0; i < checkboxes.length; i++) { //loop the array
if (checkboxes[i].checked) { //if the array item at this index is checked, then add it to the list
bookChoices += "\n" + checkboxes[i].value;
}
}
if (bookChoices == "") {
window.alert("You must select at least one book category.");
return false;
} else {
alert(bookChoices); //just for testing
return true;
}
}
See https://jsfiddle.net/7qh5segc/3/ for a demo using the changed validChoice() function.
I have the code below. I want my max character input to be 10 and min to be 2. But I tried and my textbox still changed to red when my minimum character entered was 2 or even less than 10 characters. I can't HTML maxlength or minlength here.
This condition if (fname.value.match(/\S/)) checks if the textbox is not empty when it should check for whitespaces. I tried to use != "", but when I enter something it gets skipped when I debug this.
function validation() {
var fname = "";
var add = "";
var message = "";
// retrieving ids
fname = document.getElementById('fname');
add = document.getElementById('add');
// white to red
if (fname.value.match(/\S/)) {
fname.style.backgroundColor = "white";
}
if ((fname != '') || (fname.value >= 10 || fname.value <= 2)) {
fname.style.backgroundColor = "red";
}
// white to red
if (add.value.match(/\S/)) {
add.style.backgroundColor = "white";
}
if ((add != '') || (add.value >= 10 || add.value <= 2)) {
add.style.backgroundColor = "red";
}
if (fname.value == "") {
alert("Firstname is empty! Enter your firstname to resume");
return false;
}
if (add.value == "") {
alert("Address is empty! Enter your address to resume");
return false;
}
}
<form onsubmit="return validation()">
Firstname:<br>
<input type="text" name="fname" id="fname">
<br> Address:
<br>
<input type="text" name="add" id="add">
<br><br>
<input type="submit" onClick="validation(); return false;" value="Submit">
</form>
You should check if the value's length is between 2 and 10, not the value itself. Like this:
function validation() {
var fname = document.getElementById('fname');
var add = document.getElementById('add');
if (2 <= fname.value.length && fname.value.length <= 10) { // if there is input between 2 and 10 characters, then set the background to white
fname.style.backgroundColor = "white";
}else { // otherwise, ...
fname.style.backgroundColor = "red";
alert("name is not valid!");
return false;
}
if (2 <= add.value.length && add.value.length <= 10) { // if there is input between 2 and 10 characters, then set the background to white
add.style.backgroundColor = "white";
}
else { // otherwise, ...
add.style.backgroundColor = "red";
alert("addres is not valid!");
return false;
}
return true;
}
<form onsubmit="return validation()">
Firstname:<br>
<input type="text" name="fname" id="fname">
<br> Address:
<br>
<input type="text" name="add" id="add">
<br><br>
<input type="submit" onClick="validation(); return false;" value="Submit">
</form>
I am developing a simple address book. I am using four different arrays to store name,phone no ,address and email of user.When I am calling add() method its adding values to these arrays,but when I am calling display the details its showing address book empty and all these arrays empty. Thanks in advance please help..
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Address Book</title>
<link rel="stylesheet" type="text/css" href="addressBook.css" />
<script src="jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
$('#add').click(function () {
add();
});
$('#delete').click(function () {
remove_con();
});
$('#view').click(function () {
display();
});
});
</script>
<script type="text/javascript">
var BOOK = new Array();
var BOOKNO = new Array();
var ADDR = new Array();
var EMAIL = new Array();
function add() {
//Take values from text fields
var conname = document.getElementById('userNam').value;
var lenname = BOOK.length;
var x = BOOK.indexOf(conname);
var conno = document.getElementById('userNo').value;
var lenno = BOOKNO.length;
var y = BOOKNO.indexOf(conno);
var conaddr = document.getElementById('userAdd').value;
var lenaddr = ADDR.length;
var z = ADDR.indexOf(conaddr);
var conemail = document.getElementById('userEmail').value;
var lenemail = EMAIL.length;
var w = EMAIL.indexOf(conemail);
//Validations
if (conname.length == 0) {
alert("Name field cannot be blank");
return;
}
else if (conno.length == 0) {
alert("Phone number field cannot be Left blank");
return;
}
else if (conno.length != 10) {
alert("Enter a Valid Phone Number");
return;
}
else if (conaddr.length == 0) {
alert("Address field cannot be blank");
return;
}
else if (conemail.length == 0) {
alert("Email field cannot be blank");
return;
}
//RegEX
alphaExp = /^[a-zA-Z]+$/;
numExp = /^[0-9]+$/;
betaExp = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!conname.match(alphaExp)) {
alert("Please enter alphabets only");
return;
}
else if (!conno.match(numExp)) {
alert("Please enter numerals only");
return;
}
else if (!conemail.match(betaExp)) {
alert("Please enter a valid email");
return;
}
else if (y >= 0) {
alert("Phone number already Present");
return;
}
else {
BOOK[lenname] = conname;
BOOKNO[lenno] = conno;
ADDR[lenaddr] = conaddr;
EMAIL[lenemail] = conemail;
var l = BOOK.length;
alert("Contact " + conname + " Added Sucesfully!!!!" +l);
return BOOK,BOOKNO,ADDR,EMAIL;
}
}
function display() {
//document.getElementById('hiddenDiv').style.display = "block";
BOOK = BOOK.sort();
var l = BOOK.length;
alert(l);
var view = "";
if (l == 0) {
document.getElementById('hiddenDiv').innerHTML = "ADDRESS BOOK EMPTY!!!";
}
if (l >= 1) {
view = view + "<table border=1px><tr><td><B>NAME</B></td><td><B>PHONE NUMBER</B></td><td><B>ADDRESS</B></td><td><B>EMAIL</B></td>";
for (var i = 0; i < BOOK.length; i++) {
view = view + "<tr><td>" + BOOK[i] + "</td><td>" + BOOKNO[i] + "</td><td>" + ADDR[i] + "</td><td>" + EMAIL[i] + "</td></tr>";
}
document.getElementById('hiddenDiv').innerHTML = view + "</table>";
}
}
function remove_con() {
var remname = prompt("Enter the name to be removed");
var remlen = BOOK.LENGTH;
/*var remnam=document.getElementById('name').value;
var remno=document.getElementById('phno').value;*/
var z = BOOK.indexOf(remname);
var z1 = z;
var z2 = z;
var z3 = z;
if (remlen == 0) {
alert("ADDRESS BOOK IS EMPTY");
return;
}
if (z >= 0) {
BOOK.splice(z, 1);
BOOKNO.splice(z1, 1);
ADDR.splice(z2, 1);
EMAIL.splice(z3, 1);
alert("Contact deleted");
}
if (z == -1) {
alert("Contact not present");
}
}
function searchcon() {
var lenn1 = BOOK.length;
if (lenn1 == 0) {
alert("ADDRESS BOOK EMPTY");
return;
}
var coname = prompt("Enter name");
var ind = BOOK.indexOf(coname);
if (ind >= 0) {
alert("contact found");
return;
}
else {
alert("Contact not present in address book");
}
}
</script>
</head>
<body>
<div id="mainDiv">
<header id="startHeader">
<p id="headerPara">Welcome to Address Book</p>
</header>
<div id="midDiv">
<form id="submissionForm">
<div class="entryDiv">
<p class="inputType">Name:</p>
<input id="userNam" type="text" class="buttonsClass" placeholder="Enter Your Name" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Number:</p>
<input id="userNo" type="text" class="buttonsClass" placeholder="Enter Your Number" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Address:</p>
<input id="userAdd" type="text" class="buttonsClass" placeholder="Enter Your Address" required="" />
</div>
<div class="entryDiv">
<p class="inputType">Email:</p>
<input id="userEmail" type="email" class="buttonsClass" placeholder="Enter Your Email" required="" />
</div>
<div id="Buttons">
<input id="reset" type="reset" value="Reset" />
<input id="delete" type="button" value="Delete Contact" />
<input id="view" type="button" value="View Book" />
<input id="add" type="submit" value="AddToContacts" />
</div>
</form>
<div id="hiddenDiv">
</div>
</div>
</div>
</body>
</html>
Change add button's type "submit" to "button" then remove return statement from add function as it is not needed.
This code has many issues.
You don't need four array to store address detail. you can make one array that can have objects containing the address information.eg.
var Address=function(name,address,email,mobile){
this.name=name;
this.address=address||"not available";
this.email=email||"not available";
this.mobile=mobile;
}
var AddressBook=new Array();
//Adding data in address book
AddressBook.push(new Address("jhon","baker street","a#in.com","049372497"))
You can use jquery to get value of element instead of pure javascript. eg.
var conname = document.getElementById('userNam').value;
//instead of this use jquery
var conname=$("#userNam").val(); // recommended approach
There is no need to calculate array length everywhere.To check duplicate mobile number you can write a function.
there are many other improvement you can have in code. for more examples go through Jquery site and Github public repositories.
Fiddle Demo
Change the <input id="add" type="submit" value="AddToContacts" /> to type="button". type="submit" will refresh the page to form's action and will reset all variables including BOOK.
I am having a ini.jsp page for creating a form for adding two text fields to input date and then using javascript in the ini.jsp page itself to validate those dates. I now have some library files(calendar.js, calendar-en.js, calendar-setup.js, calendar_1.png, calendar_system.css).
Now my question is how to I link these files to javascript (I am using ECLIPSE IDE) so that it displays calendar beside the textboxes for date in the format dd/mm/yyyy. . .
I have gone through lots of stuff, tried doing those but really couldn't get the expected output.
Below is the code that i have implemented so far
<html lang="en">
<head>
<style type="text/css" src="../datePickers/calendar-system.css">
</style>
</head>
<body>
<script language="Javascript" src="../Scripts/calendar.js"></script>
<h1>Report Generation</h1>
<div style="margin: 0 auto; width: 100%; text-align: left">
<form name="date" action="<c:url value="cli.htm"/>"
method="post" onSubmit="return ValidateForm()">
<fieldset>
<legend>Please enter Start Date and End Date</legend>
<div style="text-align: center; margin: 150px auto 100px auto;">
<label for="dateFrom">Start Date:</label>
<font color="#CC0000"><b>(dd/mm /yyyy)</b></font>
<input type="text" name="dateFrom" maxlength="25" size="25"
id="dateFrom" />
<img src = "../Images/calendar_1.png" onclick="javascript:Calendar.setup(inputField,ifFormat,button) style="cursor: pointer" />
</div>
<div style="text-align: center; margin: 150px auto 100px auto;">
<label for="dateTo">End Date:</label>
<font color="#CC0000"><b>(dd/mm/yyyy)</b></font>
<input type="text" name="dateTo" maxlength="25" size="25"
id="dateTo" />
</div>
<div>
<input type="submit" value="Generate Report" align="center" />
</div>
</form>
</div>
<script language="Javascript" >
var dtCh= "/";
var minYear=1900;
var maxYear=2500;
function isInteger(s){
var i;
for (i = 0; i < s.length; i++){
// Checking that the current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9")))
return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag){
var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++){
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
function daysInFebruary (year){
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
for (var i = 1; i <= n; i++) {
this[i] = 31
if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
if (i==2) {this[i] = 29}
}
return this
}
function isDate(dtStr){
var daysInMonth = DaysArray(12)
var pos1=dtStr.indexOf(dtCh)
var pos2=dtStr.indexOf(dtCh,pos1+1)
var strDay=dtStr.substring(0,pos1)
var strMonth=dtStr.substring(pos1+1,pos2)
var strYear=dtStr.substring(pos2+1)
strYr = strYear
if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
for (var i = 1; i <= 3; i++) {
if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
}
month=parseInt(strMonth)
day=parseInt(strDay)
year=parseInt(strYr)
if (pos1==-1 || pos2==-1){
alert("The date format should be : dd/mm/yyyy");
return false;
}
if (strMonth.length<1 || month<1 || month>12){
alert("Please enter a valid month");
return false;
}
if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
alert("Please enter a valid day");
return false;
}
if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
return false;
}
if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))== false){
alert("Please enter a valid date");
return false;
}
return true;
}
function ValidateForm(){
var dt1=document.date.dateFrom
var dt2=document.date.dateTo
if (!isDate(dt1.value)){
dt1.value='';
dt1.focus();
return false;
}
if(!isDate(dt2.value)){
dt2.value='';
dt2.focus();
return false;
}
return true
}
}
</script>
</body>
</html>
I want changes in code to be done as:
The code should initialises the calendar object and links an image to a text field (using their IDs) to respond to a click.
Calendar.setup(
{
inputField : "dateFrom", // ID of the input field
ifFormat : "%d/%m/%Y", // the date format
button : "imgCal" // ID of the calendar image
}
);
should I really need to create a calendar object if so, can I know where. Also, where should I place the Calendar.setup code in my jsp page?
Can someone please help me sort out this issue...
Quick suggestion: Have you tried looking into this page.
Easy to implement and you can see the demo as well.
http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/
**
Now, Looking into your code; can you please flick the calender.setup(foo1, foo2...) function implementation? (Is this your customized library?)
Thanks,
i am trying to validate date with **YYYY\MM\DD of format using HTML and Javascript
Hope its Help you...
try to yourself...
< script type = "text/javascript" >
function valdate() {
var regdate = /^(19[0-9][0-9]|20[0-9][0-9])\/(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])$/;
if (form1.txtdate.value.match(regdate)) {
return true;
} else {
alert("! please Enter the Date in this Format 'YYYY/MM/DD'");
form1.txtdate.value = "";
form1.txtdate.focus();
return false;
}
} < /script>
<from="form1" method="post" action="">
<input name="txtdate" type="text" onblur="valdate()" maxlength="10" required />
</form>
if helpful so make voting....