Checking Radio Button Value in Javascript - 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');
}

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 '

AngularJS ng-repeat data record creation with Collapse-Expand area

I am attempting to create records repeatedly using ng-repeat and the data portion of the record need to be collapsible. I tried collapsible and working fine (I have added the script at the top of the page) but the collapsible portion is not working for the repeated records.
Can somebody tell me what I am missing ?
<!DOCTYPE>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
</head>
<style>
.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
.active, .collapsible:hover {
background-color: #555;
}
.collapsible:after {
content: 'Edit';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "Done Editting";
}
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
</style>
<body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Customers = [
];
$scope.Add = function () {
var customer = {};
customer.Type = $scope.AccType;
customer.Name = $scope.Name;
customer.Country = $scope.Country;
$scope.Customers.push(customer);
$scope.Type = "";
$scope.Name = "";
$scope.Country = "";
};
$scope.Remove = function (index) {
var name = $scope.Customers[index].Name;
if ($window.confirm("Do you want to delete " + name)) {
$scope.Customers.splice(index, 1);
}
}
});
</script>
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
</script>
<button type="button" class="collapsible">This is working</button>
<div class="content">
<p>Enter your account information:</p>
<tr>
<label for="ftype">Acc. Type:</label>
<td><input type="text" value=""></td>
<td><label for="ftype">Name:</label>
<input type="text" value=""></td>
<td><label for="ftype">Country:</label>
<input type="text" value=""></td>
<td><input type="button" value="Delete"></td><br><br>
</tr>
</div>
<br>
<div ng-app="MyApp" ng-controller="MyController">
<table cellpadding="0" cellspacing="10">
<tbody ng-repeat="m in Customers">
<tr>
<td>
<button class="collapsible">{{m.Name}}</button>
<div class="content">
<p>Notes</p>
</div>
</td>
<td><input type="text" value="{{m.AccType}}" /></td>
<td><input type="text" value="{{m.Name}}" /></td>
<td><input type="text" value="{{m.Country}}" /></td>
<td><input type="button" ng-click="Remove($index)" value="Delete" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<form>
<label for="type">Account Type:</label><br>
<input type="text" ng-model="Type" id="type" name="type" value=""><br>
<label for="name">Name:</label><br>
<input type="text" ng-model="Name" id="name" name="name" value=""><br>
<label for="country">Country:</label><br>
<input type="text" ng-model="Country" id="country" name="country" value="">
<input type="button" ng-click="Add()" value="Add" />
</form>
</td>
</tr>
</tfoot>
</table>
</div>
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
</script>
</body>
</html>
you can do this in very simple steps:
add ng-click="isopen = !isopen" on which you add click event.
add ng-if ="isopen" to the row which you want collapsible.
suppose you have rows like below and on clicking first tr tag you have to open second trrow. so just do it like below.
<table>
<tr ng-click="isopen = !isopen"></tr>
<tr ng-if ="isopen"></tr>
</table>

How to add and delete new row with new values each time using JavaScript?

I have been given a task to make 2 HTML pages, one with form where the user enter his/her contact information and another where the user's information are viewed in a table.
I just need to use these languages only (JavaScript, jquery, HTML, CSS ,bootstrap); no use of PHP/JSP, only client-side language
and no database should be used. Up until now I have done this much.
$(function()
{
$('#form').validate(
{
rules:
{
email:
{required:true,
email:true
},
gender:
{required:true
},
cont:{
required:true,
number:true}
}
})
});
function onsumit(){
localStorage.setItem("input0",1);
var ip=document.getElementById("name");
localStorage.setItem("input1", ip.value);
var ip2=document.getElementById("email");
localStorage.setItem("input2", ip2.value);
var ip3=document.getElementById("cont");
localStorage.setItem("input3", ip3.value);
var ip4=document.getElementById("gender");
localStorage.setItem("input4", ip4.value);
var ip5=document.getElementById("comment");
localStorage.setItem("input5", ip5.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"
type="text/javascript"></script>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a> CONTACT FORM</a>
<form class="table-responsive" id="form" name="form" action="next.html" method="get" onsubmit="onsumit()" >
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name"required>*<p id="p1"></p></td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont"required>*<p id="p2"></p></td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email"required>*<p id="p3"></p></td>
</tr>
<tr>
<td>Gender:</td>
<td><select id="gender" name="gender" required>
<option value="" >SELECT</option>
<option value="male">MALE</option>
<option value="female">FEMALE</option>
</select>*<p id="p4"></p></td>
</tr>
<tr>
<td>comments:</td>
<td> <textarea class="form-control" rows="5" id="comment" maxlength="100"></textarea>
</td>
</tr>
</table>
<label><input id="submit" type="submit" value="SUBMIT"></label>
</form>
</div>
now this is the second html page.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
body {
font: 20px Montserrat, sans-serif;
line-height: 1.8;
color: black;
}
p {font-size: 16px;}
.margin {margin-bottom: 45px;}
.bg-1 {
background-color: #1abc9c; /* Green */
color: #ffffff;
}
.bg-2 {
background-color: #474e5d; /* Dark Blue */
color: #ffffff;
}
.bg-3 {
background-color: #ffffff; /* White */
color: #555555;
}
.bg-4 {
background-color: #2f2f2f; /* Black Gray */
color: #fff;
}
.container-fluid {
padding-top: 70px;
padding-bottom: 70px;
}
.navbar {
padding-top: 15px;
padding-bottom: 15px;
border: 0;
border-radius: 0;
margin-bottom: 0;
font-size: 12px;
letter-spacing: 5px;
}
.navbar-nav li a:hover {
color: #1abc9c !important;
}
#divmid {
margin:20px;
padding:20px;
border:3px solid red;
}
table{
text-align:left ;
}
th, td {
padding: 20px;
text-align:left;
}
textarea{
max-height:300px;
resize:none;
}
#div1{
text-align:center;
}
#tab2 {
text-align:left ;
border:2px solid red;
margin-left:auto;
margin-top:40px;
margin-bottom:200px;
}
#pick{
padding:100px;
}
<style>
table, td,th{
border: 1px solid black;
}
</style>
<body onload="load()">
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>S No.</th>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
<th>GENDER</th>
<th>COMMENTS</th>
<th>EDIT</th>
</tr>
</table>
</div>
</body>
The problem is I need to create a row in second page each time a user input with the new values in the form, but what in have done, it only creating one row and always updating it with the new values. Though I have used Local storage but still I am stuck here.
The problem is in the line 6 of your code. The parameter 1 passed to the insertRow function instantiates the variable row with the first row of your table. This way, every time you use insertCell in the row variable it updates the value on this first row. I think switching to rowCount + 1 will do the job.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(rowCount + 1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
take a look at this code. I think it should be what you are looking for.
Everytime the form is submitted, I first get the value of the local storage and add the new entry as JSON.
On the other page, I get the local storage, transform the value to get an object from the JSON string and use that object to show the informations inside the table.
Hope this help!
First Page :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function onsumit() {
if (typeof(Storage) !== "undefined") {
// Exemple of str : {'d' : [{'name':'Mister A','cont':'1',email':'MisterA#test.com'},{'name':'Mister B','cont':'1','email':'MisterB#test.com'}]}
var str = localStorage.getItem("contactinformation");
var contactModel;
if (str !== '') {
contactModel = JSON.parse(str);
} else {
contactModel = {
d : []
};
}
contactModel.d[contactModel.d.length] = {
name:$('#name').val(),
cont:$('#cont').val(),
email:$('#email').val()
}
localStorage.setItem("contactinformation",JSON.stringify(contactModel));
return true;
} else {
// Sorry! No Web Storage support..
return false;
}
}
</script>
</head>
<body>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a>CONTACT FORM</a>
<form id="form" name="form" action="next.html" method="get" onsubmit="return onsumit();">
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name">*</td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont">*</td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email">*</td>
</tr>
</table>
<input id="submit" type="submit" value="SUBMIT">
</form>
</div>
</body>
</html>
Second Page :
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
table, td,th{
border: 1px solid black;
}
</style>
</head>
<body>
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
if (typeof(Storage) !== "undefined") {
var str = localStorage.getItem("contactinformation");
var info = JSON.parse(str);
if (typeof(info.d) !== "undefined") {
for (var x=0;x<info.d.length;x++) {
$('#tab2').append('<tr><td>' + info.d[x].name + '</td><td>' + info.d[x].cont + '</td><td>' + info.d[x].email + '</td></tr>');
}
}
}
});
</script>
</body>
</html>

Javascript Validation not working properly [duplicate]

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

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