Hi I try to include a Captcha script inside a .Tpl form but if I write the correct email and not fill the captcha Simple the form jump the captcha
The form look to word and the captcha show the numbers. I try different combinations with onsubmit="return checkform(this);" value="{{$submit}}
but nothing look to words
any ideas please?
<div class="generic-content-wrapper-styled">
<h3>{{$title}}</h3>
<p id="lostpass-desc">
{{$desc}}
</p>
<form action="lostpass" method="post" >
<div id="login-name-wrapper">
<label for="login-name" id="label-login-name">{{$name}}</label>
<input type="text" maxlength="60" name="login-name" id="login-name" value="" />
<input type="submit" name="submit" id="lostpass-submit-button" onsubmit="return checkform(this);" value="{{$submit}}"/>
</div>
<!-- START CAPTCHA -->
<br>
<div class="capbox">
<div id="CaptchaDiv"></div>
<div class="capbox-inner">
Type the above number:<br>
<input type="hidden" id="txtCaptcha">
<input type="text" name="CaptchaInput" id="CaptchaInput" size="15"><br>
</div>
</div>
<br><br>
<!-- END CAPTCHA -->
<div id="login-extra-end"></div>
<div id="login-submit-end"></div>
</form>
<script type="text/javascript">
// Captcha Script
function checkform(theform){
var why = "";
if(theform.CaptchaInput.value == ""){
why += "- Please Enter CAPTCHA Code.\n";
}
if(theform.CaptchaInput.value != ""){
if(ValidCaptcha(theform.CaptchaInput.value) == false){
why += "- The CAPTCHA Code Does Not Match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("CaptchaDiv").innerHTML = code;
// Validate input against the generated number
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('CaptchaInput').value);
if (str1 == str2){
return true;
}else{
return false;
notice( t('No valid account found.') . EOL);
goaway(z_root());
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</div>
Related
I have problem with coding html and js. the alert is not appearing upon submitting and i was following the template entirely. Anyone are able to find what is the problem? im sure my script file is in the same directory and the file is linked after i had tested by using document.write(""). And also what i wish the web page to do is to alert(gErrorMsg).
This is the html part
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="./styles/style1.css">
<script src="script.js"></script>
</head>
<body>
<header>
<img id="images" src = "Logo.png" alt="Photo of Logo"/>
</header>
<nav>
<ul>
<li>Contact Us |</li>
<li>Jobs at Swinburne |</li>
<li>Copyright and disclaimer |</li>
<li>Privacy |</li>
<li>Accesibility |</li>
<li>Feedback |</li>
<li>Register</li>
</ul>
</nav>
<form id="regForm" method="post" action="" validate="novalidate">
<fieldset>
<legend>Personal Details:</legend>
<label for="fname">Name:</label><input type="text" id="fname" name="fname" placeholder="Your name" required="required"/>*<br/>
<label for="fmail">Email:</label><input type="text" id="fmail" name="fmail" placeholder="Your email" required="required"/>*<br/>
<label for="fdob">Date of birth:</label><input type="text" id="fdob" name="fdob" placeholder="dd/mm/yy"/>
</fieldset>
<fieldset>
<legend>Your unit</legend>
<input type="radio" value="cos10011" name="radio" id="COS10011" />COS10011
<input type="radio" value="cos60004" name="radio" id="COS60004" />COS60004
<input type="radio" value="cos60007" name="radio" id="COS60007" />COS60007<br/>
<label for="tutor">Your Tutor:</label>
<select name="tutor" id="tutor">
<option value="none">-------</option>
<option value="t1">Tutor 1</option>
<option value="t2">Tutor 2</option>
<option value="t3">Tutor 3</option>
<option value="other">Other</option>
</select>
</fieldset>
<fieldset id="issue">
<legend >Issue</legend>
<input type="checkbox" name="html" value="html"/>HTML
<input type="checkbox" name="css" value="css"/>CSS
<input type="checkbox" name="javascript" value="jss"/>JavaScript
<input type="checkbox" name="php" value="php"/>PHP
<input type="checkbox" name="mysql" value="sql"/>MySQL
<br/><br/>
<label for="comments">Description of Issue</label><br/>
<textarea name="comments" id="comments" rows="5" cols="20" placeholder="Enter comments header"></textarea>
</fieldset>
<fieldset>
<legend>Preferred Date/Time</legend>
<label for="date">Date:</label>
<input type="date" id="date" name="date"/><br/>
<label for="time">Time:</label>
<input type="time" id="time" name="time"/>
</fieldset>
<input type= "submit" value="Register"/>
<input type= "reset" value="Reset"/>
</form>
</body>
</html>
this is the Javascript part
var gErrorMsg = "";
function init() {
var regForm = document.getElementById("regForm");
regForm.onsubmit = validateForm;
}
window.onload = init;
function validateForm(){
"use strict"; //directive to ensure variables are declared
var isAllOK = false;
gErrorMsg = ""; //reset error message
var nameOK = chkName();
var emailOK = chkEmail();
var tutorOK = chkTutor();
var dobOK = isDobOK();
var unitOK = isUnitSelected();
var issueOK = isIssueSelected();
if (nameOK && emailOK && issueOK && dobOK && tutorOK && unitOK){
isAllOK = true;
}
else{
alert(gErrorMsg); //display concatenated error messages
gErrorMsg = ""; //reset error msg
isAllOK = false;
}
return isAllOK;
}
// check name valid format
// demo: nested single branch if statements
// demo: string property and regular expression pattern
function chkName () {
var name = document.getElementById("fname").value;
var pattern = /^[a-zA-Z ]+$/ //check only alpha characters or space
var nameOk = true;
if (name==""){
gErrorMsg = gErrorMsg + "Your name cannot be blank\n"
nameOk = false; //if condition or clause complex more readable if branches on separate lines
}
else{
if (!pattern.test(name)){
gErrorMsg = gErrorMsg + "Your name must only contain alpha characters\n"
nameOk = false;
}
}
return nameOk;
}
//check the pattern of email(regular expression)
// demo: two branch if statement with then
function chkEmail () {
var email = document.getElementById("fmail").value;
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email)){
result = true;
}
else{ //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address\n"
}
return result;
}
function chkTutor(){
var selected = false;
var tutor = document.getElementById("tutor").value;
if (tutor!="none"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select your tutor\n"
}
return selected;
}
//demo String and Date methods
//demo array index
//check date format is (sort of) ok
// check cat is born and less than 20 yo.
function isDobOK(){
var validDOB = true; //set to false if not ok
var now = new Date(); //current date-time
var dob = document.getElementById("fdob").value;
var dateMsg = "";
//assume format dd/mm/yyyy
var dmy = dob.split("/"); //split date into array with elements dd mm yyy
var allNumbers = true;
for (var i = 0; i < dmy.length; i++){
if(isNaN(dmy[i])){
dateMsg = dateMsg + "You must enter only numbers into the date" + "\n";
validDOB = false;
}
}
if ((dmy[0] <1) || (dmy[0] > 31)){ //day
dateMsg = dateMsg + "Day must be between 1 and 31" + "\n";
validDOB = false;
}
if ((dmy[1] <1) || (dmy[1] > 12)){ //month
dateMsg = dateMsg + "Month must be between 1 and 12" + "\n";
validDOB = false;
}
if ((dmy[2] < now.getFullYear() - 60)) { //dmy[2] = year
dateMsg = dateMsg + "Invalid DOB, you are too old to register" + "\n";
validDOB = false;
}
if (dmy[2] > now.getFullYear()){
dateMsg = dateMsg + "Invalid DOB, you are not born yet." + "\n";
validDOB = false;
}
if (!validDOB){
gErrorMsg = gErrorMsg + dateMsg;
}
return validDOB;
}
//check male or female has been selected
function isUnitSelected(){
var selected = false;
var is11 = document.getElementById("COS10011").checked;
var is04 = document.getElementById("COS60004").checked;
var is07 = document.getElementById("COS60007").checked;
if (is11 || is04 || is07)
selected = true; //we haven't used {}. BE CAREFUL about adding extra lines
else{
selected = false;
gErrorMsg = gErrorMsg + "Please select your unit\n"
}
return selected;
}
//demo counted for loop
/* Use parallel arrays of label and input to check at least one check box is selected
then construct an error message from the labels on the web page
Note: more checkboxes can be added to the html without affecting the JS code
*/
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = labels[i].firstChild.textContent;
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n" + unitList;
}
return selected;
}
This is your issue: you're using some undefined variables. Double check your HTML or if the variable is initialized.
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = labels[i].firstChild.textContent; // ERROR: labels[i] is undefined
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n" + unitList; // ERROR: unitList is undefined
}
return selected;
}
Working Demo
var gErrorMsg = "";
function init() {
var regForm = document.getElementById("regForm");
regForm.onsubmit = validateForm;
}
window.onload = init;
function validateForm(e){
e.preventDefault(); // Necessary for some reason...
"use strict"; //directive to ensure variables are declared
var isAllOK = false;
gErrorMsg = ""; //reset error message
var nameOK = chkName();
var emailOK = chkEmail();
var tutorOK = chkTutor();
var dobOK = isDobOK();
var unitOK = isUnitSelected();
var issueOK = isIssueSelected();
if (nameOK && emailOK && issueOK && dobOK && tutorOK && unitOK){
isAllOK = true;
}
else{
alert(gErrorMsg); //display concatenated error messages
gErrorMsg = ""; //reset error msg
isAllOK = false;
}
return isAllOK;
}
// check name valid format
// demo: nested single branch if statements
// demo: string property and regular expression pattern
function chkName () {
var name = document.getElementById("fname").value;
var pattern = /^[a-zA-Z ]+$/ //check only alpha characters or space
var nameOk = true;
if (name==""){
gErrorMsg = gErrorMsg + "Your name cannot be blank\n"
nameOk = false; //if condition or clause complex more readable if branches on separate lines
}
else{
if (!pattern.test(name)){
gErrorMsg = gErrorMsg + "Your name must only contain alpha characters\n"
nameOk = false;
}
}
return nameOk;
}
//check the pattern of email(regular expression)
// demo: two branch if statement with then
function chkEmail () {
var email = document.getElementById("fmail").value;
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email)){
result = true;
}
else{ //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address\n"
}
return result;
}
function chkTutor(){
var selected = false;
var tutor = document.getElementById("tutor").value;
if (tutor!="none"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select your tutor\n"
}
return selected;
}
//demo String and Date methods
//demo array index
//check date format is (sort of) ok
// check cat is born and less than 20 yo.
function isDobOK(){
var validDOB = true; //set to false if not ok
var now = new Date(); //current date-time
var dob = document.getElementById("fdob").value;
var dateMsg = "";
//assume format dd/mm/yyyy
var dmy = dob.split("/"); //split date into array with elements dd mm yyy
var allNumbers = true;
for (var i = 0; i < dmy.length; i++){
if(isNaN(dmy[i])){
dateMsg = dateMsg + "You must enter only numbers into the date" + "\n";
validDOB = false;
}
}
if ((dmy[0] <1) || (dmy[0] > 31)){ //day
dateMsg = dateMsg + "Day must be between 1 and 31" + "\n";
validDOB = false;
}
if ((dmy[1] <1) || (dmy[1] > 12)){ //month
dateMsg = dateMsg + "Month must be between 1 and 12" + "\n";
validDOB = false;
}
if ((dmy[2] < now.getFullYear() - 60)) { //dmy[2] = year
dateMsg = dateMsg + "Invalid DOB, you are too old to register" + "\n";
validDOB = false;
}
if (dmy[2] > now.getFullYear()){
dateMsg = dateMsg + "Invalid DOB, you are not born yet." + "\n";
validDOB = false;
}
if (!validDOB){
gErrorMsg = gErrorMsg + dateMsg;
}
return validDOB;
}
//check male or female has been selected
function isUnitSelected(){
var selected = false;
var is11 = document.getElementById("COS10011").checked;
var is04 = document.getElementById("COS60004").checked;
var is07 = document.getElementById("COS60007").checked;
if (is11 || is04 || is07)
selected = true; //we haven't used {}. BE CAREFUL about adding extra lines
else{
selected = false;
gErrorMsg = gErrorMsg + "Please select your unit\n"
}
return selected;
}
//demo counted for loop
/* Use parallel arrays of label and input to check at least one check box is selected
then construct an error message from the labels on the web page
Note: more checkboxes can be added to the html without affecting the JS code
*/
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = ""; //labels[i].firstChild.textContent; // ERROR: labels[i] is undefined
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n"; // + unitList; // ERROR: unitList is undefined
}
return selected;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="./styles/style1.css">
<script src="script.js"></script>
</head>
<body>
<header>
<img id="images" src = "Logo.png" alt="Photo of Logo"/>
</header>
<nav>
<ul>
<li>Contact Us |</li>
<li>Jobs at Swinburne |</li>
<li>Copyright and disclaimer |</li>
<li>Privacy |</li>
<li>Accesibility |</li>
<li>Feedback |</li>
<li>Register</li>
</ul>
</nav>
<form id="regForm" method="post" action="">
<fieldset>
<legend>Personal Details:</legend>
<label for="fname">Name:</label><input type="text" id="fname" name="fname" placeholder="Your name" required="required"/>*<br/>
<label for="fmail">Email:</label><input type="text" id="fmail" name="fmail" placeholder="Your email" required="required"/>*<br/>
<label for="fdob">Date of birth:</label><input type="text" id="fdob" name="fdob" placeholder="dd/mm/yy"/>
</fieldset>
<fieldset>
<legend>Your unit</legend>
<input type="radio" value="cos10011" name="radio" id="COS10011" />COS10011
<input type="radio" value="cos60004" name="radio" id="COS60004" />COS60004
<input type="radio" value="cos60007" name="radio" id="COS60007" />COS60007<br/>
<label for="tutor">Your Tutor:</label>
<select name="tutor" id="tutor">
<option value="none">-------</option>
<option value="t1">Tutor 1</option>
<option value="t2">Tutor 2</option>
<option value="t3">Tutor 3</option>
<option value="other">Other</option>
</select>
</fieldset>
<fieldset id="issue">
<legend >Issue</legend>
<input type="checkbox" name="html" value="html"/>HTML
<input type="checkbox" name="css" value="css"/>CSS
<input type="checkbox" name="javascript" value="jss"/>JavaScript
<input type="checkbox" name="php" value="php"/>PHP
<input type="checkbox" name="mysql" value="sql"/>MySQL
<br/><br/>
<label for="comments">Description of Issue</label><br/>
<textarea name="comments" id="comments" rows="5" cols="20" placeholder="Enter comments header"></textarea>
</fieldset>
<fieldset>
<legend>Preferred Date/Time</legend>
<label for="date">Date:</label>
<input type="date" id="date" name="date"/><br/>
<label for="time">Time:</label>
<input type="time" id="time" name="time"/>
</fieldset>
<input type= "submit" value="Register"/>
<input type= "reset" value="Reset"/>
</form>
</body>
</html>
I'm trying to use validation on input field for Employee salary
calculation form by using javascript.
The calculation code works fine, however it can't validate input field before proceeding with calculation.
Here the code.
function validateForm() {
var x = document.forms["myForm"]["employeename"]["employeeno"].value;
if (x == "") {
alert("Please fill up Empty field");
return false;
}
}
function paySalary() {
var employeeName = document.getElementById("employeename").value;
var employeeNo = document.getElementById("employeeno").value;
var employeeHours = document.getElementById("hours").value;
var HoursRate = document.getElementById("rate").value;
if (employeeHours <= 40) {
var regtime = HoursRate * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (HoursRate * 40);
var overtime = ((HoursRate * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
alert("Paid ammout for " + employeeName + " is for RM " + salary );
}
<body>
<form name="myForm" action="" onsubmit="return checkForm(this)" method="post">
<label>Employee Name :</label>
<input id="employeename" value=""><br>
<label>Employee No :</label>
<input id="employeeno" value=""><br>
<label>Rate of pay :</label>
<input id="rate" value=""><br>
<label>Hours Work :</label>
<input id="hours" value=""><br>
<br>
<button id="submit" onclick="paySalary()" >Submit</button>
</form>
<br>
<br>
</body>
The paySalary() function will be executed as soon as you click the submit button and before the form validation. What you can do is writting the validateForm() inside the paySalary() function. If the conditions pass the test then continue..
function validateForm() {
var x = document.getElementById("employeeno").value;
if (x == "") {
alert("Please fill up Empty field");
return false;
}
return true;
}
function paySalary() {
// If the form is not valid: stop execution
if(!validateForm()) {
return;
}
var employeeName = document.getElementById("employeename").value;
var employeeNo = document.getElementById("employeeno").value;
var employeeHours = document.getElementById("hours").value;
var HoursRate = document.getElementById("rate").value;
if (employeeHours <= 40) {
var regtime = HoursRate * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (HoursRate * 40);
var overtime = ((HoursRate * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
alert("Paid ammout for " + employeeName + " is for RM " + salary )
}
<body>
<form name="myForm" action="" onsubmit="return paySalary()" method="post">
<label>Employee Name :</label>
<input id="employeename" value="Bob"><br>
<label>Employee No :</label>
<input id="employeeno"><br>
<label>Rate of pay :</label>
<input id="rate" value="0"><br>
<label>Hours Work :</label>
<input id="hours" value="0"><br>
<br>
<button id="submit">Submit</button>
</form>
<br>
<br>
</body>
I want to create a captcha to stop spammers, but don not have the knowhow to use php and MySql to create server-side validation.
Any help would be appreciated...
I'd recommend to use a static "dummy.html" for the , because simple spammers will parse this and send an HTTP post request, bypassing the captcha validation.
For serious spammers, a client-side solution will never suffice.
Here's a basic implementation of what I mean:
https://jsfiddle.net/goyqdv7z/1/
<html>
<!-- action="invalid_captcha.html" IMPORTANT! SEE BELOW.! -->
<form method="post" id="idForm" action="invalid_captcha.html">
Form text goes here...<br/>
<div id="idCaptcha"/></div>
<input type="submit" value="Go!">
</form>
// 1. add a <div id="idCaptcha" into your <form action="invalid_caption.html" />
// 2. Replace the ULR
function CreateCaptcha() {
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var captchaCode = a + ' ' + b + ' ' + ' ' + c + ' ' + d ;
document.getElementById("idCaptcha").innerHTML =
'<div >Please type the following figures: '+a+', '+b+', number '+c+' and number '+d+'</div>'
+'<input type="text" id="txtInputCaptcha" onkeyup="onChangeCaptcha();">'
+'<input type="hidden" id="idCaptchaHidden" value="'+captchaCode+'">'
;
}
CreateCaptcha();
function ValidCaptcha() { // valida los numeros ingresados
var str1 = removeSpaces(document.getElementById('idCaptchaHidden').value);
var str2 = removeSpaces(document.getElementById('txtInputCaptcha').value);
return (str1 == str2);
}
function removeSpaces(string) {
return string.split(' ').join('').split(',').join('');
}
function onChangeCaptcha(){
if(ValidCaptcha()){
var form = document.getElementById("idForm");
form.action = form.action.replace("invalid_captcha.html", "mailform.php");
form.style="background-color:#cfc;";
document.getElementById("idCaptcha").style='display:none;';
}
}
</html>
HTML:
<!DOCTYPE html>
<html>
<head><title>JS Captcha by Ian L. of Jafty.com</title>
<style>
body{
background-color: #430000;
}
</style>
</head>
<body>
<form name="review" ACTION="newpg.html" METHOD="POST" onsubmit="return checkform(this);">
<font color="#DD0000">Enter Code ></font> <span id="txtCaptchaDiv" style="background-color:#A51D22;color:#FFF;padding:5px"></span>
<input type="hidden" id="txtCaptcha" />
<input type="text" name="txtInput" id="txtInput" size="15" />
<input type="submit" value="Submit"/>
</form>
Javascript:
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
This is just a simple one with no styling, however it works fine.
There are many automatic third party solutions for captchas such as ReCaptcha. But here you can find the explanationon how such technology actually works
I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">
first time on the website, anyway my problem is that when I use onkeydown and then use GetChar to check if the enter key was pressed, when operAtion runs,the results of the function only shows on the screen for about a second and then goes away, if the user uses the onclick (clicks the enter button), then this problem doesnt occur. How do I get the result of operAtion to stay on the screen when onkeydown is used. The website is sqrtcalc.comze.com if you want to see what I mean
sqrtcalc
<!DOCTYPE html>
<html>
<head>
<title>Square Root Calculator</title>
<script language="javascript">
function operAtion (form){
var x = form.inputbox.value;
if (isNaN(x)){
//document.write("lawl");
var y = "Enter a number";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x < 0){
var y = "Number must be positive";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x == ""){
var y = "uhm, you didnt enter anything";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else {
var y = Math.pow(x, 1/2)
document.getElementById("demo").innerHTML = "The square root of " + x + " is " + y;
document.getElementById("failsafe").innerHTML = "";
}
}
function GetChar (event,form){
var keyCode = event.keyCode;
if (keyCode == 13){
operAtion(form);
}
}
</script>
<p></p>
</head>
<body>
<form name="myform" action="" method="get" style = "font-size:50px"><strong>Square Root Calculator</strong></br>
</br>
<input type="text" name="inputbox" value = "" onkeydown = "GetChar(event,this.form);"> </br>
</br>
<input id="button" type="button" name="button" value=" Enter " onclick="operAtion(this.form)" >
</form>
<h1 id = "failsafe"></h1>
</br>
</br>
</br>
<h1 id = "demo"></h1>
</br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br></br>
<img border="0" src="http://counter.rapidcounter.com/counter/1353157574/a"; ALIGN="middle" HSPACE="4" VSPACE="2" style = "padding-left:1400px;">
</body>
</html>
Add this code:
window.onload = function(){
document.getElementById("myform").onsubmit = function(){
return false;
}
}
And add the id attribute id="myform" to the <form> tag.
I refactored your code a little:
I removed your inline functions (inline JS isn't exactly best
practice)
I added an ID to your form so it could be referenced
I added return false; to keep the form from submitting
onsubmit handles both click and enter
Javascript
document.getElementById('myform').onsubmit = function() {
var x = this.inputbox.value;
if (isNaN(x)) {
//document.write("lawl");
var y = "Enter a number";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x < 0) {
var y = "Number must be positive";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else if (x == "") {
var y = "uhm, you didnt enter anything";
document.getElementById("failsafe").innerHTML = y;
document.getElementById("demo").innerHTML = "";
} else {
var y = Math.pow(x, 1 / 2)
document.getElementById("demo").innerHTML = "The square root of " + x + " is " + y;
document.getElementById("failsafe").innerHTML = "";
}
return false;
}
HTML
<form name="myform" action="" method="get" style="font-size:50px" id="myform"><strong>Square Root Calculator</strong><br>
<br>
<input type="text" name="inputbox"> <br>
<br>
<input id="button" type="submit" name="button" value=" Enter ">
</form>
<h1 id="failsafe"></h1>
<h1 id="demo"></h1>
Working demo