Javascript Validation not working properly [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
when i click on submit button nothing happen.
error showing:
Form.js:102
Uncaught TypeError: Cannot set property 'onsubmit' of null.
cannot understand properly......
// JavaScript Document
function validate()
{
var x = document.forms["myForm"]["ide"].value;
var regex = /^[1-9]{1}[0-9]{9}$/;
if (x == null || x == "")
{
alert("Enter Your ID Number");
return false;
}
else if (!regex.test(x))
{
alert("ID Contain Numbers Only");
return false;
}
var x = document.forms["myForm"]["EName"].value;
var regex = /^[A-Za-z]+$/;
if (x == null || x == "")
{
alert("Enter Your Employee Name");
return false;
}
else if (!regex.test(x))
{
alert("Employee Name Contain Alphabets Only");
return false;
}
var x = document.forms["myForm"]["myEmail"].value;
if (x == null || x == "")
{
alert("Enter Your Email Id")
return false;
}
if((document.myForm.gender[0].checked==false)&&(document.myForm.gender[1].checked==false))
{
document.myForm.gender[0].focus();
alert("Please select a gender.");
return false;
}
var x = document.forms["myForm"]["Cnum"].value;
var regex = /^[1-9]{1}[0-9]{9}$/;
if(x == null || x == "")
{
alert("Please enter the Contact number.");
return false;
}
else if(isNaN(x))
{
alert("Contact number should contain only digits.");
return false;
}
else if(x.length!=10)
{
alert("Contact number should contain only 10 digits.(Mobile number)");
return false;
}
else if(!regex.test(x))
{
alert("Invalid Contact number.");
return false;
}
var x = document.forms["myForm"]["desig"].value;
var regex = /^[A-Za-z]+$/;
if (x == null || x == "")
{
alert("Enter Your Designation");
return false;
}
else if (!regex.test(x))
{
alert("Designation Contain Alphabets Only");
return false;
}
var x = document.forms["myForm"]["quali"].value;
var regex = /^[A-Za-z]+$/;
if (x == null || x == "")
{
alert("Enter Your Qualification");
return false;
}
else if (!regex.test(x))
{
alert("Qualification Contain Alphabets Only");
return false;
}
var x = document.forms["myForm"]["depart"].value;
if (x == null || x == "")
{
alert("Select Department");
return false;
}
}
document.getElementById("myForm").onsubmit = function ()
{
return validate(this);
};
body
{
background-image:url(img/one.jpg);
background-size:cover;
margin-left: 0px;
margin-right: 0px;
display:flex;
}
table
{
padding-top: 50px;
margin: -36px 0px 0px 124px;
}
td
{
padding: 0px 40px 0px 0px;
}
p
{
font-family: Corbel;
margin: 16px 0px 0px 0px;
font-size: 20px;
color: white;
}
.text
{
font-weight: bold;
}
.sumbit
{
margin: 30px 0px 0px 58px;
padding: 12px 0px 12px 0px;
font-size: 26px;
background-color: black;
color: white;
border: 1px solid black;
width: 674px;
}
.choose
{
color:white;
}
.hobby
{
margin-left:10px;
}
.area
{
border: 0px solid;
border-radius: 12px;
padding: 6px 6px 6px 6px;
}
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<link rel="stylesheet" href="PHP_Form.css" type="text/css">
</head>
<body>
<div>
<img src="img/2-1.png" style="height:658px"; width="109%">
</div>
<script type="text/javascript" src="PHP_Form.js"></script>
<div>
<form method="post" name="myForm" action="" id="myForm">
<table>
<tr>
<td class="text"><p>ID</p></td>
<td><p><input type="text" name="ide" class="area"></p></td>
</tr>
<tr>
<td class="text"><p>Emplyoee Name</p></td>
<td><p><input type="text" name="EName" class="area"></p></td>
</tr>
<tr>
<td class="text"><p>Designation</p></td>
<td><p><input type="text" name="desig" class="area"></p></td>
</tr>
<tr>
<td class="text"><p>Department</p></td>
<td><p>
<select class="area" id="depart">
<option value="hr">HR</option>
<option value="manager">Manager</option>
<option value="operation">Operation</option>
<option value="administrator">Administrator</option>
</select>
</p></td>
</tr>
<tr>
<td class="text"><p>Gender</p></td>
<td><p class="choose">
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
</p></td>
</tr>
<tr>
<td class="text"><p>Qualification</p></td>
<td><p><input type="text" name="quali" class="area"></p></td>
</tr>
<tr>
<td class="text"><p>Hobbies</p></td>
<td><p class="choose">
<input type="checkbox" name="hobby" value="read">Reading
<input type="checkbox" name="hobby" value="play" class="hobby">Playing
<input type="checkbox" name="hobby" value="sing" class="hobby">Singing
<input type="checkbox" name="hobby" value="dance" class="hobby">Dancing
</p></td>
</tr>
<tr>
<td class="text"><p>Email id</p></td>
<td><p><input type="email" name="email" id="myEmail" class="area" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$"></p></td>
</tr>
<tr>
<td class="text"><p>Contact</p></td>
<td><p><input type="text" name="Cnum" class="area"></p></td>
</tr>
<tr>
<td class="text"><p>Resposibilities</p></td>
<td><p><textarea id="respons" name="respons" rows="6" cols="22" class="area"></textarea></p></td>
</tr>
</table>
<input type="submit" value="Submit" class="sumbit">
</form>
</div>
</body>
</html>
Name of my file is :
Form.html
Form.js
Form.css

you execute your script before page is loaded so that
document.getElementById("myForm") returns undefined
easiest solution to fix this would be to move your
<script type="text/javascript" src="PHP_Form.js"></script>
just before </body>
if you want better solution - use DOMContentLoaded event

Related

How to unhide a div based on two Boolean function outputs

I am trying to use an input box to check if the input begins with a letter A-M, and secondly if the number of characters is odd or even, then unhide a div if these conditions are met. I am getting one error:
Uncaught TypeError: Cannot read property 'value' of null
at org.html:89
Code below.
Thanks.
I am trying to change the display style with my if statement at the end of the functions.
However, because of the null type error nothing happens.
If I can get the first one to work, I intend to duplicate the method for the other tables.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ITP-03</title>
<meta name="description" content="A calculator">
<style>
.title{
border: 10px;
margin-bottom: 10px;
text-align:center;
width: 210px;
color:black;
border: solid black 1px;
font-family: sans-serif;
}
input[type="button"]
{
border: 10px;
background-color:#46eb34;
color: black;
border-color:#46eb34 ;
width:100%;
}
input[type="text"]
{
border: 10px;
text-align: right;
background-color:white;
border-color: black ;
width:100%
}
input[type="username"]
{
border: 10px;
margin-bottom: 10px;
text-align: left;
color: black;
border: solid #46eb34 1px;
background-color:white;
border-color: black ;
width:20%
}
</style>
<script>
//function for displaying values
function dis(val)
{
document.getElementById("calc").value+=val;
}
//function for evaluation
function solve()
{
let x = document.getElementById("calc").value;
let y = eval(x);
document.getElementById("calc").value = y;
}
//function for clearing the display
function clr()
{
document.getElementById("calc").value = "";
}
function isEven()
{
var value = document.getElementById("username").value.length;
if (value%2 == 0) {
document.getElementById("check2").innerHTML = "even";
return true;
}
if (value%2 !=0) {
document.getElementById("check2").innerHTML = "odd";
return false;
}
}
function beforeN(value) {
var firstletter = document.getElementById("username").value.substring(0,1);
var str = "abcdefghijklm.";
if (str.includes(firstletter)){
document.getElementById("check1").innerHTML = "a-m";
return true;
}
else {
document.getElementById("check1").innerHTML = "n-z";
return false;
}
}
if(beforeN(document.getElementById("username").value) && (isEven(document.getElementById("username").value))){
document.getElementById("amodd").style.display= "block";
}
</script>
</head>
<body>
<p id="check1">a</p>
<p id="check2">a</p>
<p class = title>Enter your iu username</p>
<input type="username" id="username" name="iu username"/>
<br>
<button onclick=beforeN(document.getElementById("username").value) type ="button">Submit</button>
<div id ="amodd" style=display:none>
<div class = title >ITP-03 Calculator A-M ODD</div>
<table border="1">
<tr>
<td><input type="button" value="c" onclick="clr()"/> </td>
<td colspan="3"><input type="text" id="calc"/></td>
</tr>
<tr>
<td><input type="button" value="+" onclick="dis('+')"/> </td>
<td><input type="button" value="1" onclick="dis('1')"/> </td>
<td><input type="button" value="3" onclick="dis('3')"/> </td>
</tr>
<tr>
<td><input type="button" value="/" onclick="dis('/)"/> </td>
<td><input type="button" value="5" onclick="dis('5')"/> </td>
<td><input type="button" value="7" onclick="dis('7')"/> </td>
</tr>
<tr>
<td><input type="button" value="." onclick="dis('.')"/> </td>
<td><input type="button" value="9" onclick="dis('9')"/> </td>
<td><input type="button" value="=" onclick="solve()"/> </td>
</tr>
</table>
</div>
</body>
Few things to note here.
You are missing the quotes for the onclick attribute value. Others have already pointed that out.
The error that you were seeing is because your if condition resides outside a function. So, it will be executed on page load in the order in which you have written it. If you have it before the body, it will be executed before the DOM loads. In such cases, you should put it within the body at the end.
Also, the if condition will only be executed when your page loads. Since your button has an onclick attribute, it will execute only that function that you invoke. That will not help you update the page(hide and unhide divs) every time the button is clicked. I would suggest you put the if-condition within a function and invoke the function on the button click.
Also note that I have changed your if condition to remove all the parameters you were passing, since you were not using it. You were fetching the values again in your function.
Also, since you want both beforeN and isEven functions to be executed every time the button is clicked, I have changed it to execute the functions and store the result in a variable. Otherwise, it will only execute the isEven method if beforeN evaluates to true. Also included an else condition to hide the div when the conditions are not met.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ITP-03</title>
<meta name="description" content="A calculator">
<style>
.title {
border: 10px;
margin-bottom: 10px;
text-align: center;
width: 210px;
color: black;
border: solid black 1px;
font-family: sans-serif;
}
input[type="button"] {
border: 10px;
background-color: #46eb34;
color: black;
border-color: #46eb34;
width: 100%;
}
input[type="text"] {
border: 10px;
text-align: right;
background-color: white;
border-color: black;
width: 100%
}
input[type="username"] {
border: 10px;
margin-bottom: 10px;
text-align: left;
color: black;
border: solid #46eb34 1px;
background-color: white;
border-color: black;
width: 20%
}
</style>
</head>
<body>
<p id="check1">a</p>
<p id="check2">a</p>
<p class=title>Enter your iu username</p>
<input type="username" id="username" name="iu username" />
<br>
<button onclick="exFun()" type="button">Submit</button>
<div id="amodd" style=display:none>
<div class=title>ITP-03 Calculator A-M ODD</div>
<table border="1">
<tr>
<td><input type="button" value="c" onclick="clr()" /> </td>
<td colspan="3"><input type="text" id="calc" /></td>
</tr>
<tr>
<td><input type="button" value="+" onclick="dis('+')" /> </td>
<td><input type="button" value="1" onclick="dis('1')" /> </td>
<td><input type="button" value="3" onclick="dis('3')" /> </td>
</tr>
<tr>
<td><input type="button" value="/" onclick="dis('/)" /> </td>
<td><input type="button" value="5" onclick="dis('5')" /> </td>
<td><input type="button" value="7" onclick="dis('7')" /> </td>
</tr>
<tr>
<td><input type="button" value="." onclick="dis('.')" /> </td>
<td><input type="button" value="9" onclick="dis('9')" /> </td>
<td><input type="button" value="=" onclick="solve()" /> </td>
</tr>
</table>
</div>
<script>
//function for displaying values
function dis(val) {
document.getElementById("calc").value += val;
}
//function for evaluation
function solve() {
let x = document.getElementById("calc").value;
let y = eval(x);
document.getElementById("calc").value = y;
}
//function for clearing the display
function clr() {
document.getElementById("calc").value = "";
}
function isEven() {
var value = document.getElementById("username").value.length;
if (value % 2 == 0) {
document.getElementById("check2").innerHTML = "even";
return true;
}
if (value % 2 != 0) {
document.getElementById("check2").innerHTML = "odd";
return false;
}
}
function beforeN(value) {
var firstletter = document.getElementById("username").value.substring(0, 1);
var str = "abcdefghijklm.";
if (str.includes(firstletter)) {
document.getElementById("check1").innerHTML = "a-m";
return true;
}
else {
document.getElementById("check1").innerHTML = "n-z";
return false;
}
}
function exFun() {
var beforeNResult = beforeN();
var isEvenResult = isEven();
if (beforeNResult && isEvenResult) {
document.getElementById("amodd").style.display = "block";
}else{
document.getElementById("amodd").style.display = "none";
}
}
</script>
</body>
you should put script after element.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ITP-03</title>
<meta name="description" content="A calculator">
<style>
.title{
border: 10px;
margin-bottom: 10px;
text-align:center;
width: 210px;
color:black;
border: solid black 1px;
font-family: sans-serif;
}
input[type="button"]
{
border: 10px;
background-color:#46eb34;
color: black;
border-color:#46eb34 ;
width:100%;
}
input[type="text"]
{
border: 10px;
text-align: right;
background-color:white;
border-color: black ;
width:100%
}
input[type="username"]
{
border: 10px;
margin-bottom: 10px;
text-align: left;
color: black;
border: solid #46eb34 1px;
background-color:white;
border-color: black ;
width:20%
}
</style>
</head>
<body>
<p id="check1">a</p>
<p id="check2">a</p>
<p class = title>Enter your iu username</p>
<input type="username" id="username" name="iu username"/>
<br>
<button onclick='beforeN(document.getElementById("username").value)' type ="button">Submit</button>
<div id ="amodd" style=display:none>
<div class = title >ITP-03 Calculator A-M ODD</div>
<table border="1">
<tr>
<td><input type="button" value="c" onclick="clr()"/> </td>
<td colspan="3"><input type="text" id="calc"/></td>
</tr>
<tr>
<td><input type="button" value="+" onclick="dis('+')"/> </td>
<td><input type="button" value="1" onclick="dis('1')"/> </td>
<td><input type="button" value="3" onclick="dis('3')"/> </td>
</tr>
<tr>
<td><input type="button" value="/" onclick="dis('/')"> </td>
<td><input type="button" value="5" onclick="dis('5')"/> </td>
<td><input type="button" value="7" onclick="dis('7')"/> </td>
</tr>
<tr>
<td><input type="button" value="." onclick="dis('.')"/> </td>
<td><input type="button" value="9" onclick="dis('9')"/> </td>
<td><input type="button" value="=" onclick="solve()"/> </td>
</tr>
</table>
</div>
<script>
//function for displaying values
function dis(val)
{
document.getElementById("calc").value+=val;
}
//function for evaluation
function solve()
{
let x = document.getElementById("calc").value;
let y = eval(x);
document.getElementById("calc").value = y;
}
//function for clearing the display
function clr()
{
document.getElementById("calc").value = "";
}
function isEven()
{
var value = document.getElementById("username").value.length;
if (value%2 == 0) {
document.getElementById("check2").innerHTML = "even";
return true;
}
if (value%2 !=0) {
document.getElementById("check2").innerHTML = "odd";
return false;
}
}
function beforeN(value) {
var firstletter = document.getElementById("username").value.substring(0,1);
var str = "abcdefghijklm.";
if (str.includes(firstletter)){
document.getElementById("check1").innerHTML = "a-m";
return true;
}
else {
document.getElementById("check1").innerHTML = "n-z";
return false;
}
}
if(beforeN(document.getElementById("username").value) && (isEven(document.getElementById("username").value))){
document.getElementById("amodd").style.display= "block";
}
</script>
</body>
and in this line
<button onclick='beforeN(document.getElementById("username").value)' type ="button">Submit</button>
you missed '

Checking Radio Button Value in Javascript

I am developing a sample project named: Tennis Club Management using javascript,HTML,CSS,Bootstrap. In this project, I have a managePlayers.html page in which there are two buttons Add Players & Show Players. On clicking Add Players button, a table with input fields appears below, which contains ID,DOB,Name,Gender,Contact, 2 radio buttons for gender a SAVE button..
Note : What i need to do is that when i click the save button , it should check whether either of the radio is selected or not (Gender : male/female ..in this case). I couldn't figured it out yet.Below are the code files and screenshots
Jsfiddle link : https://jsfiddle.net/mohitsharma1991/40yz7tv6/1/
index.js
//---------------------TESTING CODE FOR DISPLAYING TABLE FOR ADDING CUSTOMER INFORMATION---------------
function addplayers() {
// playerIDvalue += 1;
document.querySelector("#customerregistration").style.display = "block";
if (istableCreated) {
document.querySelector("#table-responsive").style.display = "none";
}
// document.querySelector(".playerID").value = playerIDvalue;
}
//--------------------------TESTING CODE FOR SAVING CUSTOMER INFORMATION OF MANAGE PLAYERS PAGE-----------------------------
function savePlayer() {
console.log("data saved successfully...");
var playerBirthday = document.querySelector(".playerbirthday").value;
var playerName = document.querySelector(".playername").value;
var playerContact = document.querySelector(".playercontact").value;
var playerAddress = document.querySelector(".playeraddress").value;
var playerGender = document.querySelector('input[name="gender"]:checked').value;
var playerID = document.querySelector(".playerID").value;
var customerIDProof = document.querySelector(".customeridproof").value;
var customerIDProofTextBox = document.querySelector(".customeridprooftextbox").value;
var membershipFor = document.querySelector(".membershipfor").value;
var membershipType = document.querySelector(".membershiptype").value;
//console.log(playerBirthday,playerName,playerContact,playerAddress,playerGender,customerIDProof,customerIDProofTextBox,membershipFor,membershipType);
if (playerID == "") {
document.querySelector(".playerIDlabel").innerHTML = "*Cannot be blank"
// console.log("ID cannot be blank");
}
else if (playerBirthday == "") {
document.querySelector(".playerbirthdaylabel").innerHTML = "*Select Date"
}
else if (playerContact == "") {
document.querySelector(".playercontactlabel").innerHTML = "*Cannot be blank";
}
else if (playerName == "") {
document.querySelector(".playernamelabel").innerHTML = "*Cannot be blank";
}
else if ((!playerGender == "Male") && (!playerGender == "Female")) {
document.querySelector(".genderlabel").innerHTML = "*Cannot be blank";
}
else if (playerAddress == "") {
document.querySelector(".playeraddresslabel").innerHTML = "*Cannot be blank";
}
else if (customerIDProof == "---Select---") {
document.querySelector(".customeridprooflabel").innerHTML = "*Select value";
}
else if (customerIDProofTextBox == "") {
document.querySelector(".customeridprooflabel").innerHTML = "*Cannot be blank";
}
else if (membershipFor == "---Select---") {
document.querySelector(".membershipforlabel").innerHTML = "*Select value";
}
else if (membershipType == "---Select---") {
document.querySelector(".membershiptypelabel").innerHTML = "*Select value";
}
else {
addPlayerList.push({
"ID": playerIDvalue,
"DOB": playerBirthday,
"Gender": playerGender,
"Address": playerAddress,
"IDProof": customerIDProof,
"IDProofValue": customerIDProofTextBox,
"membershipFor": membershipFor,
"membershipType": membershipType,
"playerContact": playerContact,
"playerName": playerName
});
}
console.log(addPlayerList);
return false;
}
managePlayers.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Players</title>
<!-- ADDING FONT AWESOME CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- ADDING BOOTSTRAP CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- ADDING STYLE.CSS -->
<link rel="stylesheet" href="/css/style.css">
</head>
<body class="managePlayers">
<!-- ADDING BUTTONS LIKE SHOW PLAYERS, ADD PLAYERS USING CSS BOOTSTRAP -->
<button type="button" class="btn btn-secondary showplayers" onclick="showplayers();">Show Players</button>
<button type="button" class="btn btn-secondary addplayers" onclick="addplayers()">Add Players</button>
<!-- CREATING REGISTRATION FORM OF CUSTOMER -->
<table class="customerregistration" id="customerregistration">
<tr>
<td>
<Label>ID :</Label>
</td>
<td>
<input type="text" class="playerID" id="playerID">
</td>
<td>
<label class="playerIDlabel"></label>
</td>
</tr>
<tr>
<td>
<label>DOB :</label>
</td>
<td>
<input type="date" id="playerbirthday" class="playerbirthday">
</td>
<td>
<label class="playerbirthdaylabel"></label>
</td>
</tr>
<tr>
<td>
<label>Name :</label>
</td>
<td>
<input type="text" class="playername" id="playername">
</td>
<td>
<label class="playernamelabel"></label>
</td>
</tr>
<tr>
<td>
<label>Gender :</label>
</td>
<td>
<input type="radio" name="gender" value="female" class="playergender" id="femaleplayer"> Female
<input type="radio" name="gender" value="male" class="playergender" id="maleplayer"> Male
</td>
<td>
<label class="genderlabel"></label>
</td>
</tr>
<tr>
<td>
<label>Contact :</label>
</td>
<td>
<input type="text" class="playercontact" id="playercontact">
</td>
<td>
<label class="playercontactlabel"></label>
</td>
</tr>
<tr>
<td>
<label>Address :</label>
</td>
<td>
<textarea class="playeraddress" id="playeraddress" cols="20" rows="3"></textarea>
</td>
<td>
<label class="playeraddresslabel"></label>
</td>
</tr>
<tr>
<td>
<label>ID Proof :</label>
<select class="customeridproof" id="customeridproof">
<option value="select">---Select---</option>
<option value="license">License</option>
<option value="aadhaar">Aadhaar</option>
<option value="passport">Passport</option>
</select>
</td>
<td>
<input type="text" class="customeridprooftextbox">
</td>
<td>
<label class="customeridprooflabel"></label>
</td>
</tr>
<tr>
<td>
<label>Membership For :</label>
</td>
<td>
<select class="membershipfor" id="membershipfor">
<option value="select">---Select---</option>
<option value="court">Court</option>
<option value="tournament">Tournament</option>
<option value="both">Both</option>
</select>
</td>
<td>
<label class="membershipforlabel"></label>
</td>
</tr>
<tr>
<td>
<label>Membership Type :</label>
</td>
<td>
<select class="membershiptype" id="membershiptype">
<option value="select">---Select---</option>
<option value="monthly">Monthly</option>
<option value="halfyearly">Half Yearly</option>
<option value="annually">Annually</option>
</select>
</td>
<td>
<label class="membershiptypelabel"></label>
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-success saveplayer" onclick="savePlayer()">SAVE</button>
</td>
</tr>
</table>
<!-- ADDING BOOTSTRAP JS -->
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
crossorigin="anonymous"></script>
<!-- ADDING INDEX.JS -->
<script src="/js/sidebar.js"></script>
<script src="/js/index.js"></script>
</body>
</html>
Screenshots
Any solution please ?
You can simply use checked property of your input to see which gender was checked while saving the player and push that value to your array
The checked property will return true or false for each radio button and will assign a value to your var playerGender - In the instance of that you have not selected any radio button the var playerGender will be undefined and then we can the error message.
I have added the working code in demo and if you do not select anything in the gender you will see this message *Cannot be blanked
Working Demo
// --------------TESTING CODE FOR LOGIN PAGE LOGIN BUTTON CLICK----------------
var istableCreated = false;
var email, password, playerIDvalue = 0;
var addPlayerList = [];
var addtournamentsList = [];
var addTrainersList = [];
var addMatchList = [];
var addFeesList = [];
//------------------------------------"MANAGE PLAYERS PAGE"----------------------------------
//--------------------------------TESTING CODE FOR SHOWING PLAYERS OF MANAGE PLAYERS PAGE--------------------------
function showplayers() {
document.querySelector("#customerregistration").style.display = "none";
if (istableCreated == false) {
istableCreated = true;
var myTable = document.createElement("table");
myTable.className = "table-responsive";
myTable.id = "table-responsive";
myTable.style.marginLeft = "15%";
document.body.appendChild(myTable);
var maintr = document.createElement("tr");
document.body.appendChild(myTable).appendChild(maintr);
var thID = document.createElement("th");
thID.innerHTML = "ID";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thID);
var thplayerName = document.createElement("th");
thplayerName.innerHTML = "Player Name";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thplayerName);
// var thDOB = document.createElement("th");
// thDOB.innerHTML = "DOB";
// document.body.appendChild(myTable).appendChild(maintr).appendChild(thDOB);
// var thGender = document.createElement("th");
// thGender.innerHTML = "Gender";
// document.body.appendChild(myTable).appendChild(maintr).appendChild(thGender);
var thAddress = document.createElement("th");
thAddress.innerHTML = "Address";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thAddress);
// var thIDProof = document.createElement("th");
// thIDProof.innerHTML = "ID Proof";
// document.body.appendChild(myTable).appendChild(maintr).appendChild(thIDProof);
// var thIDProofValue = document.createElement("th");
// thIDProofValue.innerHTML = "Value";
// document.body.appendChild(myTable).appendChild(maintr).appendChild(thIDProofValue);
// var thmembershipFor = document.createElement("th");
// thmembershipFor.innerHTML = "Membership For";
// document.body.appendChild(myTable).appendChild(maintr).appendChild(thmembershipFor);
// var thmembershipType = document.createElement("th");
// thmembershipType.innerHTML = "Membership Type";
// document.body.appendChild(myTable).appendChild(maintr).appendChild(thmembershipType);
var thcontact = document.createElement("th");
thcontact.innerHTML = "Contact";
document.body.appendChild(myTable).appendChild(maintr).appendChild(thcontact);
//-------------TESTING CODE FOR FETCHING ONLINE DATA FROM API AND CREATING TABLE ROWS--------------
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// console.log(this.responseText);
var JSONarr = JSON.parse(this.responseText);
console.log(JSONarr);
// ----------SUPER TESTING CODE-----------
for (var i = 0; i < JSONarr.length; i++) {
console.log(JSONarr[i].id, JSONarr[i].name, JSONarr[i].address.city, JSONarr[i].address.zipcode);
var myTr = document.createElement("tr");
document.body.appendChild(myTable).appendChild(myTr);
var tdID = document.createElement("td");
tdID.innerHTML = `${JSONarr[i].id}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdID);
var tdplayerName = document.createElement("td");
tdplayerName.innerHTML = `${JSONarr[i].name}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdplayerName);
var tdAddress = document.createElement("td");
tdAddress.innerHTML = `${JSONarr[i].address.city}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdAddress);
var tdContact = document.createElement("td");
tdContact.innerHTML = `${JSONarr[i].phone}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdContact);
}
}
};
xhttp.open("GET", "https://jsonplaceholder.typicode.com/users", true);
xhttp.send();
/*
for (var i = 0; i < addPlayerList.length; i++) {
console.log(addPlayerList.length);
var myTr = document.createElement("tr");
document.body.appendChild(myTable).appendChild(myTr);
var tdID = document.createElement("td");
tdID.innerHTML = `${addPlayerList[i].ID}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdID);
var tdplayerName = document.createElement("td");
tdplayerName.innerHTML = `${addPlayerList[i].playerName}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdplayerName);
var tdDOB = document.createElement("td");
tdDOB.innerHTML = `${addPlayerList[i].DOB}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdDOB);
var tdGender = document.createElement("td");
tdGender.innerHTML = `${addPlayerList[i].Gender}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdGender);
var tdAddress = document.createElement("td");
tdAddress.innerHTML = `${addPlayerList[i].Address}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdAddress);
var tdIDProof = document.createElement("td");
tdIDProof.innerHTML = `${addPlayerList[i].IDProof}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdIDProof);
var tdIDProofValue = document.createElement("td");
tdIDProofValue.innerHTML = `${addPlayerList[i].IDProofValue}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdIDProofValue);
var tdmembershipFor = document.createElement("td");
tdmembershipFor.innerHTML = `${addPlayerList[i].membershipFor}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdmembershipFor);
var tdmembershipType = document.createElement("td");
tdmembershipType.innerHTML = `${addPlayerList[i].membershipType}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdmembershipType);
var tdContact = document.createElement("td");
tdContact.innerHTML = `${addPlayerList[i].playerContact}`;
document.body.appendChild(myTable).appendChild(myTr).appendChild(tdContact);
}
*/
} else {
document.querySelector("#table-responsive").style.display = "block";
}
}
//---------------------TESTING CODE FOR DISPLAYING TABLE FOR ADDING CUSTOMER INFORMATION---------------
function addplayers() {
// playerIDvalue += 1;
document.querySelector("#customerregistration").style.display = "block";
if (istableCreated) {
document.querySelector("#table-responsive").style.display = "none";
}
// document.querySelector(".playerID").value = playerIDvalue;
}
//--------------------------TESTING CODE FOR SAVING CUSTOMER INFORMATION OF MANAGE PLAYERS PAGE-----------------------------
function savePlayer() {
console.log("data saved successfully...");
var playerBirthday = document.querySelector(".playerbirthday").value;
var playerName = document.querySelector(".playername").value;
var playerContact = document.querySelector(".playercontact").value;
var playerAddress = document.querySelector(".playeraddress").value;
var playerID = document.querySelector(".playerID").value;
var playerGender
if (document.getElementById('femaleplayer').checked) {
playerGender = document.getElementById('femaleplayer').value;
} else if (document.getElementById('maleplayer').checked) {
playerGender = document.getElementById('maleplayer').value;
}
if (playerGender == undefined) {
document.querySelector(".genderlabel").innerHTML = "*Cannot be blank";
}
var customerIDProof = document.querySelector(".customeridproof").value;
var customerIDProofTextBox = document.querySelector(".customeridprooftextbox").value;
var membershipFor = document.querySelector(".membershipfor").value;
var membershipType = document.querySelector(".membershiptype").value;
// console.log(playerBirthday,playerName,playerContact,playerAddress,playerGender,customerIDProof,customerIDProofTextBox,membershipFor,membershipType);
if (playerID == "") {
document.querySelector(".playerIDlabel").innerHTML = "*Cannot be blank"
// console.log("ID cannot be blank");
} else if (playerBirthday == "") {
document.querySelector(".playerbirthdaylabel").innerHTML = "*Select Date"
} else if (playerContact == "") {
document.querySelector(".playercontactlabel").innerHTML = "*Cannot be blank";
} else if (playerName == "") {
document.querySelector(".playernamelabel").innerHTML = "*Cannot be blank";
} else if ((!playerGender == "Male") && (!playerGender == "Female")) {
document.querySelector(".genderlabel").innerHTML = "*Cannot be blank";
} else if (playerAddress == "") {
document.querySelector(".playeraddresslabel").innerHTML = "*Cannot be blank";
} else if (customerIDProof == "---Select---") {
document.querySelector(".customeridprooflabel").innerHTML = "*Select value";
} else if (customerIDProofTextBox == "") {
document.querySelector(".customeridprooflabel").innerHTML = "*Cannot be blank";
} else if (membershipFor == "---Select---") {
document.querySelector(".membershipforlabel").innerHTML = "*Select value";
} else if (membershipType == "---Select---") {
document.querySelector(".membershiptypelabel").innerHTML = "*Select value";
} else {
addPlayerList.push({
"ID": playerIDvalue,
"DOB": playerBirthday,
"Gender": playerGender,
"Address": playerAddress,
"IDProof": customerIDProof,
"IDProofValue": customerIDProofTextBox,
"membershipFor": membershipFor,
"membershipType": membershipType,
"playerContact": playerContact,
"playerName": playerName
});
}
console.log(addPlayerList);
return false;
}
form {
margin: auto;
/* nice thing of auto margin if display:flex; it center both horizontal and vertical :) */
width: 30%;
}
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 25%;
height: 25%;
margin-top: 3%;
margin-bottom: 1.5%;
}
.login {
display: table-cell;
text-align: center;
vertical-align: middle;
}
label {
font-weight: bolder;
}
.labelemailpassworderror {
color: red;
font-size: 10px;
text-align: left;
}
.labelemailerror {
color: red;
font-size: 10px;
text-align: center;
}
.labelpassworderror {
color: red;
font-size: 10px;
text-align: center;
}
h3 {
text-align: center;
}
h5 {
text-align: center;
color: green;
}
.forgotpassword {
text-align: center;
font-size: 10px;
/* margin-left: 25%; */
}
.signup {
text-align: center;
font-size: 10px;
}
span {
color: #1a73e8;
}
span:hover {
color: purple;
}
/* ---------------- SETTING CSS PROPERTIES OF PROFILE PAGE---------------- */
body {
margin-top: 0;
font-family: "Lato", sans-serif;
}
.sidebar {
top: 0;
left: 0;
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
position: fixed;
height: 100%;
overflow: auto;
}
.sidebar a {
display: block;
color: black;
padding: 16px;
text-decoration: none;
}
.sidebar a.active {
background-color: #4CAF50;
color: white;
}
.sidebar a:hover:not(.active) {
background-color: #555;
color: white;
}
div.content {
margin-left: 200px;
padding: 1px 16px;
height: 1000px;
}
#media screen and (max-width: 700px) {
.sidebar {
width: 100%;
height: auto;
position: relative;
}
.sidebar a {
float: left;
}
div.content {
margin-left: 0;
}
}
#media screen and (max-width: 400px) {
.sidebar a {
text-align: center;
float: none;
}
}
.editadminprofile {
float: right;
}
/* ---------------- SETTING CSS PROPERTIES OF MANAGE PLAYERS PAGE---------------- */
.showplayers {
margin-right: 30%;
margin-top: 5%;
margin-bottom: 2%;
float: right;
width: 15%;
}
.addplayers {
margin-right: 3%;
margin-top: 5%;
margin-bottom: 2%;
float: right;
width: 15%;
}
.playeraddress {
resize: none;
}
/* ---------------- SETTING CSS PROPERTIES OF MANAGE TRAINERS PAGE---------------- */
.showtrainers {
margin-right: 30%;
margin-top: 5%;
float: right;
width: 15%;
}
.addtrainers {
margin-right: 3%;
margin-top: 5%;
float: right;
width: 15%;
}
/* ---------------- SETTING CSS PROPERTIES OF MANAGE TOURNAMENTS PAGE---------------- */
.showtournaments {
margin-right: 30%;
margin-top: 5%;
float: right;
width: 15%;
}
.addtournaments {
margin-right: 3%;
margin-top: 5%;
float: right;
width: 15%;
}
/* ---------------- SETTING CSS PROPERTIES OF MANAGE MATCHES PAGE---------------- */
.showmatches {
margin-right: 30%;
margin-top: 5%;
float: right;
width: 15%;
}
.addmatches {
margin-right: 3%;
margin-top: 5%;
float: right;
width: 15%;
}
/* ---------------- SETTING CSS PROPERTIES OF MANAGE FEES PAGE---------------- */
.showfees {
margin-right: 30%;
margin-top: 5%;
float: right;
width: 15%;
}
.addfees {
margin-right: 3%;
margin-top: 5%;
float: right;
width: 15%;
}
/* ---------------- SETTING CSS PROPERTIES OF TABLE OF MANAGE PLAYER PAGE ---------------- */
table {
table-layout: fixed;
}
table th,
table td {
overflow: hidden;
}
th {
width: 5%;
}
/*-------------- SETING CSS PROPERTIES OF CUSTOMER REGISTRATION FORM-------------*/
.customerregistration {
margin-top: 5%;
display: none;
float: right;
margin-right: 30%;
}
.customeraddress {
resize: none;
}
/*-------------- SETING CSS PROPERTIES OF TRAINER REGISTRATION FORM-------------*/
.trainerregistration {
margin-top: 5%;
float: right;
margin-right: 32%;
display: none;
}
.traineraddress {
resize: none;
}
/*-------------- SETING CSS PROPERTIES OF TOURNAMENT REGISTRATION FORM-------------*/
.tournamentregistration {
display: none;
margin-top: 5%;
float: right;
margin-right: 32%;
}
/*---------------SETTING CSS PROPERTIES OF MATCH REGISTRATION-----------------*/
.matchregistration {
display: none;
margin-top: 5%;
float: right;
margin-right: 35%;
}
/* -------------SETTING CSS PROPERTIES OF MANAGE FEES---------------------- */
.feesregistration {
margin-top: 5%;
float: right;
margin-right: 35%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Players</title>
<!-- ADDING FONT AWESOME CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- ADDING BOOTSTRAP CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- ADDING STYLE.CSS -->
<link rel="stylesheet" href="/css/style.css">
</head>
<body class="managePlayers">
<!-- ADDING BUTTONS LIKE SHOW PLAYERS, ADD PLAYERS USING CSS BOOTSTRAP -->
<button type="button" class="btn btn-secondary showplayers" onclick="showplayers();">Show Players</button>
<button type="button" class="btn btn-secondary addplayers" onclick="addplayers()">Add Players</button>
<!-- CREATING REGISTRATION FORM OF CUSTOMER -->
<table class="customerregistration" id="customerregistration">
<tr>
<td>
<Label>ID :</Label>
</td>
<td>
<input type="text" class="playerID" id="playerID">
</td>
<td>
<label class="playerIDlabel"></label>
</td>
</tr>
<tr>
<td>
<label>DOB :</label>
</td>
<td>
<input type="date" id="playerbirthday" class="playerbirthday">
</td>
<td>
<label class="playerbirthdaylabel"></label>
</td>
</tr>
<tr>
<td>
<label>Name :</label>
</td>
<td>
<input type="text" class="playername" id="playername">
</td>
<td>
<label class="playernamelabel"></label>
</td>
</tr>
<tr>
<td>
<label>Gender :</label>
</td>
<td>
<input type="radio" name="gender" value="female" class="playergender" id="femaleplayer" required> Female
<input type="radio" name="gender" value="male" class="playergender" id="maleplayer" required> Male
</td>
<td>
<label class="genderlabel"></label>
</td>
</tr>
<tr>
<td>
<label>Contact :</label>
</td>
<td>
<input type="text" class="playercontact" id="playercontact">
</td>
<td>
<label class="playercontactlabel"></label>
</td>
</tr>
<tr>
<td>
<label>Address :</label>
</td>
<td>
<textarea class="playeraddress" id="playeraddress" cols="20" rows="3"></textarea>
</td>
<td>
<label class="playeraddresslabel"></label>
</td>
</tr>
<tr>
<td>
<label>ID Proof :</label>
<select class="customeridproof" id="customeridproof">
<option value="select">---Select---</option>
<option value="license">License</option>
<option value="aadhaar">Aadhaar</option>
<option value="passport">Passport</option>
</select>
</td>
<td>
<input type="text" class="customeridprooftextbox">
</td>
<td>
<label class="customeridprooflabel"></label>
</td>
</tr>
<tr>
<td>
<label>Membership For :</label>
</td>
<td>
<select class="membershipfor" id="membershipfor">
<option value="select">---Select---</option>
<option value="court">Court</option>
<option value="tournament">Tournament</option>
<option value="both">Both</option>
</select>
</td>
<td>
<label class="membershipforlabel"></label>
</td>
</tr>
<tr>
<td>
<label>Membership Type :</label>
</td>
<td>
<select class="membershiptype" id="membershiptype">
<option value="select">---Select---</option>
<option value="monthly">Monthly</option>
<option value="halfyearly">Half Yearly</option>
<option value="annually">Annually</option>
</select>
</td>
<td>
<label class="membershiptypelabel"></label>
</td>
</tr>
<tr>
<td>
<button type="button" class="btn btn-success saveplayer" onclick="savePlayer()">SAVE</button>
</td>
</tr>
</table>
<!-- ADDING BOOTSTRAP JS -->
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<!-- ADDING INDEX.JS -->
<script src="/js/sidebar.js"></script>
<script src="/js/index.js"></script>
</body>
</html>
you can try something like this
var gender = document.querySelector('input[name="gender"]').checked ;
if(gender == true){
return true;
}else {
return false;
}
use script to check whether radio input is selected or not.
//getting value of radio button
let radioInput = $('input[name=gender]:checked').val();
//checking for its value, if it is undefined nothing is selected.
if(radioInput){
//do something with value.
}else{
alert('Nothing selected');
}

Luhn Algorithm Implementation into original code

<!DOCTYPE html>
<html <head>
<meta charset="utf-8">
<title>Credit Card Number Validator</title>
<style>
<!-- .title {
font-family: "Trebuchet MS";
font-size: 30px;
font-style: oblique;
color: #006600;
text-align: center;
}
body {
background-color: #FFFFE8;
font-family: Arial, Helvetica, sans-serif;
}
table {
margin: auto;
width: 600px;
}
.right {
text-align: right;
}
.center {
text-align: center;
}
#id {
width: 175px;
}
-->
</style>
</head>
<body>
<p class="title">Validate a credit card number </p>
<form name="form1" id="form1" method="post" action="">
<table>
<tr>
<td width="219" class="right">Enter the credit card number:</td>
<td width="168" class="center"><input name="textfield" type="text" id="card"></td>
<td width="196" id="output"> </td>
</tr>
<tr>
<td height="30"> </td>
<td class="center"><input type="button" id="button" value="Test the Card Number!"></td>
<td> </td>
</tr>
</table>
</form>
<script>
document.getElementById("button").addEventListener('click', credit, false);
function credit() {
data = document.getElementById("card").value;
if (data) {
cardnum = data.replace(/[^0-9]/, "");
} else {
alert('Please enter a number to test.');
}
if (cardnum.length == 16 && cardnum.charAt(0) == "5" && cardnum.charAt(1) != "0" && cardnum.charAt(12) == "7") {
donecard = +cardnum.substr(0, 3) + " ";
document.getElementById("card").innerHTML = donecard;
document.getElementById("output").innerHTML = "valid";
} else {
document.getElementById("output").innerHTML = "invalid";
}
}
</script>
</body>
</html>
I'm trying to implement the Luhn algorithm to my code, so that it works together.
My first block works well it validates numbers correctly based off the code. This block works correctly. I want to implement the second part to it, which is the luhn algorithim with a loop or loops. What would be the best way to do this.
Something like this might work. Typed from my phone so probably has typos.
let sum = 0;
let len = cardnum.length;
for(let i=0; i = len; i++) {
let foo = cardnum.charAt(len-i)
if(i % 2 ) {
foo = foo * 2;
foo = (foo) > 9) ? foo-9 : foo;
sum = sum + foo;
} else {
sum = sum + foo
}
if( (sum * 9) % 10 === 0) {
console.log(‘valid’)
}

How to do validation and display message before form submit?

I have multiple rows of HTML input elements with type number. Each row has four input fields and I want to add validation so that any input field should not allow a value lesser than the field on it's left side (in the same row).
I want to add this same validation for every row.
I want to do this validation before form submission and display error message. (before form submission/submit button is clicked)
The leftmost row should not allow a value less than zero (as it doesn't have any input field on it's left).
Can you please suggest me how I can do this using the sample jsfiddle: Error message when text field has a value out of range
(I tried to do this using "min" option in "input" tag but works only after submit button is clicked.)
Same code as in fiddle:
<html>
<head>
<title>TestPage</title>
<meta HTTP-EQUIV="Content-Type" content="text/html; charset=iso-8859-1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
addPlusSign();
$(".btn1").click(function(){
$(".expand1").toggle();
var btn1Text = $(".btn1").text();
if(btn1Text.indexOf("+") > -1){
var temp = btn1Text.replace(/\+|\-/ig, '-');
$(".btn1").text(temp);
} else if (btn1Text.indexOf("-") > -1){
var temp = btn1Text.replace(/\+|\-/ig, '+');
$(".btn1").text(temp);
}
});
})
function addPlusSign(){
if($(".expand1")){
var btn1Text = $(".btn1").text();
$(".btn1").text(btn1Text + " [+]");
}
}
$(function () {
$('.admin-form')
//we need to save values from all inputs with class 'admin-input'
.find(':input.admin-input')
.each(function () {
//save old value in each input's data cache
$(this).data('oldValue', $(this).val())
})
.end()
.submit(function (ev) {
var changed = false;
$(':input.admin-input', this).filter(function () {
if($(this).val() != $(this).data('oldValue')){
changed = true;
}
});
if($(this).hasClass('changed') && (!changed)){
alert("None of the thresholds were changed!");
ev.preventDefault()
}
if($(this).hasClass('changed') && changed){
var allowSubmit = window.confirm("You have set a unique threshold for one or more sub-elements below. Are you sure you want to reset them all?")
if (!allowSubmit)
ev.preventDefault()
}
});
});
$(document).on('input', '.admin-input', function(){
$(this).closest('form').addClass('changed');
});
</script>
<style>
.expand1 { display: none;
}
.btn1 { cursor: pointer;
}
body {
background-color: rgb(255,255,255);
font: 15px Verdana, Helvetica, sans-serif;
}
table#t02, #t02 th, #t02 td {
border: none;
border-collapse: collapse;
font-size:95%;
font-weight:normal;
}
#button1{
position: relative;
top:50px;
left:35%;
color: white;
background-color: rgb(0,89,132);
font-weight: bold;
}
#button2{
position: relative;
top:50px;
left:50%;
color: white;
background-color: rgb(0,89,132);
font-weight: bold;
}
input[type=number] {
max-width: 50px;
}
html {
overflow-y: scroll;
}
</style>
</head>
<body>
<form id="form1" method="post" class="admin-form">
<div style="float:left; width:50%">
<br />
<br />
<table id="t02" class="table2">
<tr>
<th style="padding:0 30px 0 0;"></th>
<th></th>
<th style="padding:0 10px 0 0;">Green</th>
<th colspan="3" style="padding:0 10px 0 0">Yellow</th>
<th></th>
<th style="padding:0 10px 0 0">Red</th>
</tr>
<tr>
<td class="btn1" style="padding:0 30px 0 0;"><b>Row1 (%)</b></td>
<td>&lt</td>
<td style="padding:0 10px 0 0"><input type="number", class="admin-input", name="row1_good_high", value="5", size="3", maxlength="3"></td>
<td><input type="number", class="admin-input", name="row1_warning_low", value="5", size="3", maxlength="3"></td>
<td>-</td>
<td style="padding:0 10px 0 0"><input type="number", class="admin-input", name="row1_warning_high", value="15", size="3", maxlength="3"></td>
<td>&gt</td>
<td style="padding:0 10px 0 0"><input type="number", class="admin-input", name="row1_critical_low", value="15", size="3", maxlength="3"></td>
</tr>
<tr>
<td align="center" class="expand1">Sub Row</td>
<td class="expand1">&lt</td>
<td class="expand1"><input type="number", name="row1_good_high_Sub Row", value="5", size="3", maxlength="3"></td>
<td class="expand1"><input type="number", name="row1_warning_low_Sub Row", value="5", size="3", maxlength="3"></td>
<td class="expand1">-</td>
<td class="expand1"><input type="number", name="row1_warning_high_Sub Row", value="15", size="3", maxlength="3"></td>
<td class="expand1">&gt</td>
<td class="expand1"><input type="number", name="row1_critical_low_Sub Row", value="15", size="3", maxlength="3"></td>
</tr>
</table>
</div>
<div style="clear:both">
<input type="submit" onclick="return confirm('Are you sure you want to submit the change?')" name="submitButton" value="Submit" id="button1" style="height:50px; width:100px"/>
<input title="Set thresholds to baseline thresholds" type="submit" onclick="return confirm('Are you sure you want to set all thresholds to the baseline thresholds?')" name="resetButton" value="Reset" id="button2" style="height:50px; width:100px"/>
</div>
</form>
</body>
</html>
goog validation jquery plugin: http://jqueryvalidation.org/
you can define dependency like this:
$(".selector").validate({
rules: {
contact: {
required: true,
email: {
depends: function(element) {
return $("#contactform_email").is(":checked");
}
}
}
}
});
Thank you for your replies, Yaco Zaragoza and miralong.
Finally I was able to come up with following which does what I wanted:
<html>
<head>
<title>TestPage</title>
<meta HTTP-EQUIV="Content-Type" content="text/html; charset=iso-8859-1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
addPlusSign();
$(".btn1").click(function(){
$(".expand1").toggle();
var btn1Text = $(".btn1").text();
if(btn1Text.indexOf("+") > -1){
var temp = btn1Text.replace(/\+|\-/ig, '-');
$(".btn1").text(temp);
} else if (btn1Text.indexOf("-") > -1){
var temp = btn1Text.replace(/\+|\-/ig, '+');
$(".btn1").text(temp);
}
});
$('[id^="number"]').focusout(function() {
var current_field_name = this.id;
if (current_field_name.indexOf("_1") > -1) {
var good_high = Number(document.getElementById(current_field_name).value);
if (good_high < 0) {
alert(good_high + " is out of valid range!");
document.getElementById(current_field_name).focus();
}
} else if (current_field_name.indexOf("_2") > -1) {
var warning_low = Number(document.getElementById(current_field_name).value);
var previous_field_name_1 = current_field_name.replace(/2$/, "1");
var good_high = Number(document.getElementById(previous_field_name_1).value);
if (warning_low < good_high) {
alert(warning_low + " is out of valid range!");
document.getElementById(current_field_name).focus();
}
} else if (current_field_name.indexOf("_3") > -1) {
var warning_high = Number(document.getElementById(current_field_name).value);
var previous_field_name_1 = current_field_name.replace(/3$/, "1");
var good_high = Number(document.getElementById(previous_field_name_1).value);
var previous_field_name_2 = current_field_name.replace(/3$/, "2");
var warning_low = Number(document.getElementById(previous_field_name_2).value);
if (warning_high < warning_low) {
alert(warning_high + " is out of valid range!");
document.getElementById(current_field_name).focus();
}
} else if (current_field_name.indexOf("_4") > -1) {
var critical_low = Number(document.getElementById(current_field_name).value);
var previous_field_name_1 = current_field_name.replace(/4$/, "1");
var good_high = Number(document.getElementById(previous_field_name_1).value);
var previous_field_name_2 = current_field_name.replace(/4$/, "2");
var warning_low = Number(document.getElementById(previous_field_name_2).value);
var previous_field_name_3 = current_field_name.replace(/4$/, "3");
var warning_high = Number(document.getElementById(previous_field_name_3).value);
if (critical_low < warning_high) {
alert(critical_low + " is out of valid range!");
document.getElementById(current_field_name).focus();
}
}
});
})
function addPlusSign(){
if($(".expand1")){
var btn1Text = $(".btn1").text();
$(".btn1").text(btn1Text + " [+]");
}
}
$(function () {
$('.admin-form')
//we need to save values from all inputs with class 'admin-input'
.find(':input.admin-input')
.each(function () {
//save old value in each input's data cache
$(this).data('oldValue', $(this).val())
})
.end()
.submit(function (ev) {
var changed = false;
$(':input.admin-input', this).filter(function () {
if($(this).val() != $(this).data('oldValue')){
changed = true;
}
});
if($(this).hasClass('changed') && (!changed)){
alert("None of the thresholds were changed!");
ev.preventDefault()
}
if($(this).hasClass('changed') && changed){
var allowSubmit = window.confirm("You have set a unique threshold for one or more sub-elements below. Are you sure you want to reset them all?")
if (!allowSubmit)
ev.preventDefault()
}
});
});
$(document).on('input', '.admin-input', function(){
$(this).closest('form').addClass('changed');
});
</script>
<style>
.expand1 { display: none;
}
.btn1 { cursor: pointer;
}
body {
background-color: rgb(255,255,255);
font: 15px Verdana, Helvetica, sans-serif;
}
table#t02, #t02 th, #t02 td {
border: none;
border-collapse: collapse;
font-size:95%;
font-weight:normal;
}
#button1{
position: relative;
top:50px;
left:35%;
color: white;
background-color: rgb(0,89,132);
font-weight: bold;
}
#button2{
position: relative;
top:50px;
left:50%;
color: white;
background-color: rgb(0,89,132);
font-weight: bold;
}
input[type=number] {
max-width: 50px;
}
html {
overflow-y: scroll;
}
</style>
</head>
<body>
<form id="form1" method="post" class="admin-form">
<div style="float:left; width:50%">
<br />
<br />
<table id="t02" class="table2">
<tr>
<th style="padding:0 30px 0 0;"></th>
<th></th>
<th style="padding:0 10px 0 0;">Green</th>
<th colspan="3" style="padding:0 10px 0 0">Yellow</th>
<th></th>
<th style="padding:0 10px 0 0">Red</th>
</tr>
<tr>
<td style="padding:0 30px 0 0;">Row1</td>
<td>&lt</td>
<td style="padding:0 10px 0 0"><input type="number", name="row1_good_high", value="30", size="3", maxlength="3", id="number42_1"></td>
<td><input type="number", name="row1_warning_low", value="30", size="3", maxlength="3", id="number42_2"></td>
<td>-</td>
<td style="padding:0 10px 0 0"><input type="number", name="row1_warning_high", value="60", size="3", maxlength="3", id="number42_3"></td>
<td>&gt</td>
<td style="padding:0 10px 0 0"><input type="number", name="row1_critical_low", value="60", size="3", maxlength="3", id="number42_4"></td>
</tr>
<tr>
<td style="padding:0 30px 0 0;">SubRow</td>
<td>&lt</td>
<td style="padding:0 10px 0 0"><input type="number", name="subrow_good_high", value="30", size="3", maxlength="3", id="number12_1"></td>
<td><input type="number", name="subrow_warning_low", value="30", size="3", maxlength="3", id="number12_2"></td>
<td>-</td>
<td style="padding:0 10px 0 0"><input type="number", name="subrow_warning_high", value="60", size="3", maxlength="3", id="number12_3"></td>
<td>&gt</td>
<td style="padding:0 10px 0 0"><input type="number", name="subrow_critical_low", value="60", size="3", maxlength="3", id="number12_4"></td>
</tr>
</table>
</div>
<div style="clear:both">
<input type="submit" onclick="return confirm('Are you sure you want to submit the change?')" name="submitButton" value="Submit" id="button1" style="height:50px; width:100px"/>
<input title="Set thresholds to baseline thresholds" type="submit" onclick="return confirm('Are you sure you want to set all thresholds to the baseline thresholds?')" name="resetButton" value="Reset" id="button2" style="height:50px; width:100px"/>
</div>
</form>
</body>
</html>

Javascript Onload expected object error

I'm getting "scrollingMsg" is undefined. It's not the cause though; it was functioning before I started doing the validSalesAmt() function. Beside that, not sure if this will help find the bug, but clicking the fields in the form gave an error saying that function wasn't defined. Please, no recommendations 'you can do it this way instead' because this is an assignment for school that has to be done as is in the textbook.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Chapter 10 Shoreline State Bank</title>
<script type="text/javascript">
var adMsg = " **Did you know some used cars can have 100% loan value? Ask for details! **"
var beginPos = 0
function scrollingMsg()
{
msgForm.scrollingMsg.value=adMsg.substring(beginPos,adMsg.length)+adMsg.substring(0,beginPos)
beginPos=beginPos+1
if (beginPos>adMsg.length)
{
beginPos=0
}
window.setTimeout("scrollingMsg()",200)
}
var salesAmt
var loanAmt
var loanRate
var loanYears
function validSalesAmt()
{
var salesAmt=parseInt(homeLoanForm.SaleAmount.value,10)
if(isNaN(salesAmt)||(salesAmt <= 0))
{
alert("The sales price is not a valid number!")
homeLoanForm.SaleAmount.value = ""
homeLoanForm.SaleAmount.focus()
}
else
{
var downPmtAmt=parseInt(homeLoanForm.DownPayment.value, 10)
if(isNaN(downPmtAmt)||(downPmtAmt<=0)||(downPmtAmt>salesAmt))
{
alert("The down payment should be greater than 0 and less than the sales amount!")
homeLoanForm.DownPayment.value=""
homeLoanForm.DownPayment.focus()
}
else
{
loanAmt = salesAmt-downPmtAmt
homeLoanForm.LoanAmount.value=loanAmt
homeLoanForm.Rate.focus()
}
}
}
function CalcLoanAmt()
{
loanRate=parseFloat(homeLoanForm.Rate.value)
if (isNaN(loanRate) || (loanRate <= 0))
{
alert("The interest rate is not a valid number!")
homeLoanForm.Rate.value=""
homeLoanForm.Rate.focus()
}
else
{
loanYears=homeLoanForm.Years.value
if (isNaN(loanYears) || (loanYears < 1 || loanYears >30))
{
alert("Please select a valid number from the list (10,15,20, or 30)!")
homeLoanForm.Years.selectedIndex = 0
homeLoanForm.Years.focus()
}
else
{
var monthlyPmtAmt = monthlyPmt(loanAmt,loanRate,loanYears)
homeLoanForm.Payment.value=dollarFormat(monthlyPmtAmt.toString())
}
}
}
function monthlyPmt(loanAmt,loanRate,loanYears)
{
var interestRate = loanRate/1200
var Pmts = loanYears*12
var Amnt - loanAmt * (interestRate/(1-(1/Math.pow(1+interestRate,Pmts))))
return Amnt.toFixed(2)
}
function dollarFormat(valuein)
{
var formatValue= ""
var formatDollars= ""
formatAmt = valuein.split(".",2)
var dollars = formatAmt[0]
var dollarLen = dollars.length
if (dollarLen > 3)
{
while (dollarLen > 0)
{
tempDollars = dollars.substring(dollarLen - 3,dollarLen)
if(tempDollars.length == 3)
{
formatDollars = ","+tempDollars+formatDollars
dollarLen = dollarLen - 3
}
else
{
formatDollars = tempDollars+formatDollars
dollarLen = 0
}
}
if(formatDollars.substring(0,1) == ",")
{
dollars = formatDollars.substring(1,formatDollars.length)
}
else
dollars = formatDollars
}
var cents = formatAmt[1]
var formatValue="$"+dollars+"."+cents+
return formatValue
}
function popUpNotice()
{
open("chapter10-1notice.html","noticeWin","width-520,height=330")
}
function copyRight()
{
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
displayDateLast.innerHTML="<h6>Copyright© Shoreline State Bank"+"<br />This document was last modified "+lastModDate+".</h6>"
}
//-->
</script>
<style type="text/css">
<!--
.align-center {
text-align:center;
}
table {
margin-left: auto;
margin-right: auto;
width: 70%;
}
.block {
width: 50%;
margin-right: auto;
margin-left: auto;
}
.center-div {
width: 70%;
margin-right: auto;
margin-left: auto;
}
.header-text {
font-family: Arial, Helvetica, sans-serif;
font-size: 12pt;
font-weight: bold;
text-align: center;
}
.center-items {
text-align: center;
}
.right-align {
text-align: right;
width: 50%;
}
.left-align {
text-align: left;
width: 50%;
}
#displayDateLast {
text-align: left;
width: 50%;
margin-right: auto;
margin-left: auto;
}
-->
</style>
</head>
<body onLoad="scrollingMsg(); popUpNotice(); copyRight();">
<div class="center-div">
<p class="center-items"><img src="chapter10-1banner.jpg" alt="banner" /></p>
</div>
<div class="center-div">
<form id="msgForm">
<p style="text-align:center">
<input type="text" name="scrollingMsg" size="25" /></p>
</div>
<p style="text-align:center; font-size:16; font-weight:bold;">Home Mortgage Loan Payment Calculator</p>
<p class="block"><strong>Directions: </strong>Enter the agreed selling price, press the tab key, enter the down payment and press the tab key. The loan amount will be calculated automatically. Then enter the interest rate and the number of years for the loan and click the Calculate button.</p>
<div class="center-div">
<form id="homeLoanForm" method="post">
<table>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Sales Price:
</td>
<td class="align-left"><input type="text" name="SaleAmount" size="9" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Down Payment in Dollars
</td>
<td class="align-left"><input name="DownPayment" type="text" id="DownPayment" size="9" onBlur="validSalesAmt()" /></td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Loan Amount
</td>
<td class="align-left"><input name="LoanAmount" type="text" id="LoanAmount" size="9" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Interest Rate (e.g. 5.9):
</td>
<td class="align-left"><input name="Rate" type="text" id="Rate" size="5" maxlength="5" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="color:#cc0000;">*</span>Number of Years:
</td>
<td><select name="Years" id="Years">
<option value="0">Select Number of Years</option>
<option value=10>10</option>
<option value=15>15</option>
<option value=20>20</option>
<option value=30>30</option>
</select></td>
</tr>
<tr>
<td class="right-align">
<input name="button" type="button" value="Calculate" onClick="CalcLoanAmt()"/>
</td>
<td class="align-left">
<input name="Reset" type="reset" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="font-weight:bolder;">Monthly Payment:</span>
</td>
<td><input type="text" name="Payment" id="Payment" value=" " size="12" /></td>
</tr>
<tr>
<td colspan="2" class="align-center">
<span style="color:#cc0000; font-size:12px;">* Indicates a required field.</span>
</td>
</tr>
</table>
</form>
</div>
<div id="displayDateLast">
</div>
</body>
</html>
when the browser finds a syntax-error in a <script> he will discard the entire script-code within this script.
a simple demonstration:
<body onLoad="foo();bar();foobar();">
<script type="text/javascript">
var a + b;//syntax-error, similar to line 86 in your script
//this will not run because this script has been discarded
//because of the syntax-error above
function bar(){
alert('bar works');
}
</script>
<script type="text/javascript">
//this will run because here is no syntax-error,
//the function is available
function foo(){
alert('foo works');
}
//although this function is available too this will not run
//because of the error forced by the call of bar()
function foobar(){
alert('foobar works');
}
</script>
</body>
That's why the function scrollingMsg will be unknown, although there is no syntax-error within this function, because there are multiple syntax-errors in this script, fix them.

Categories

Resources