How to unhide a div based on two Boolean function outputs - javascript

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 '

Related

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 show calculation history in javascript when making a html-based calculator

I was trying to make an HTML-based calculator and it also displays the previous calculation history but I was confused about how to do it.
How to store the previous calculation results as a string a something else that can be used later on?
Hi, I was trying to make an HTML-based calculator and it also displays the previous calculation history but I was confused about how to do it.
How to store the previous calculation results as a string a something else that can be used later on?
<html>
<head>
<script>
//function that display value
function dis(val)
{
document.getElementById("result").value+=val
}
//function that evaluates the digit and return result
function solve()
{
let x = document.getElementById("result").value
let y = eval(x)
document.getElementById("result").value = y
}
//function that clear the display
function clr()
{
document.getElementById("result").value = ""
}
</script>
<!-- for styling -->
<style>
.title{
margin-bottom: 10px;
text-align:center;
width: 175px;
color:grey;
border: solid black 2px;
}
input[type="button"]
{
background-color:grey;
color: black;
border: solid black 2px;
width:100%
}
input[type="text"]
{
background-color:white;
border: solid black 2px;
width:100%
}
</style>
</head>
<!-- create table -->
<body>
<div class = title >ITP2 Calculator</div>
<table border="1">
<tr>
<td colspan="3"><input type="text" id="result"/></td>
<!-- clr() function will call clr to clear all value -->
</tr>
<tr>
<!-- create button and assign value to each button -->
<!-- dis("1") will call function dis to display value -->
<td><input type="button" value="1" onclick="dis('1')"/> </td>
<td><input type="button" value="3" onclick="dis('3')"/> </td>
<td><input type="button" value="+" onclick="dis('+')"/> </td>
</tr>
<tr>
<td><input type="button" value="5" onclick="dis('5')"/> </td>
<td><input type="button" value="7" onclick="dis('7')"/> </td>
<td><input type="button" value="/" onclick="dis('')"/> </td>
</tr>
<tr>
<td><input type="button" value="9" onclick="dis('9')"/> </td>
<td><input type="button" value="Clr" onclick="clr()"/> </td>
<td><input type="button" value="=" onclick="solve()"/> </td>
</tr>
</table>
</body>
</html>
Display history examples:
2+3=5
3+5=8
You could create a function, that will be saving data to some variable, and then just call this function every time you want to add something to the history. Here is an example:
let history = '';
function dis(val) {
// your code...
addToHistory(val);
}
function solve() {
// your code...
addToHistory('=' + y);
}
function clr() {
// your code...
addToHistory(' ');
}
function addToHistory(value) {
history += value;
document.getElementById('history').innerText = history;
}
You can take a look at how it's working here: JSFiddle

How to fix duplicate entries in number field in javascript

I have nine number fields to calculate. I need to check for duplicate entries in these 9 number fields and if found duplicate values, change the background color of the screen to 'red'. I'm not able to find solution for the mentioned.
I have created a table with 9 nine number fields to input the numbers and calculate the sum.
I searched for code to check for duplicate values in number fields, but found code to check for duplicate values in text fields.
<html>
<head>
<script>
function Sum() {
alert("hi");
var num1 = Number(document.getElementById("qty1").value);
var num2 = Number(document.getElementById("qty2").value);
var num3 = Number(document.getElementById("qty3").value);
var num4 = Number(document.getElementById("qty4").value);
var num5 = Number(document.getElementById("qty5").value);
var num6 = Number(document.getElementById("qty6").value);
var num7 = Number(document.getElementById("qty7").value);
var num8 = Number(document.getElementById("qty8").value);
var num9 = Number(document.getElementById("qty9").value);
var sum=num1+num2+num3+num4+num5+num6+num7+num8+num9
document.getElementById("answer").value = sum;
}
</script>
<style>
table>tbody>tr:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(odd){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(even){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(even){
background-color: green;
}
#sumtable th, #sumtable td{
padding:5px;
}
</style>
</head>
<title>Sum Box</title>
<body>
<table align="center" id="sumtable">
<tbody>
<tr>
<td>
<input type="number" placeholder="input1" value="input1"id="qty1"></td>
<td>
<input type="number" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number"placeholder="input3"value="input3"id="qty3"></td>
</tr>
<tr>
<td><input type="number" placeholder="input4" value="input4" id="qty4" ></td>
<td><input type="number" placeholder="input5" value="input5" id="qty5" ></td>
<td><input type="number" placeholder="input6" value="input6" id="qty6" ></td>
</tr>
<tr>
<td><input type="number" placeholder="input7" value="input7" id="qty7" ></td>
<td><input type="number" placeholder="input8" value="input8" id="qty8" ></td>
<td><input type="number" placeholder="input9" value="input9" id="qty9" ></td>
</tr>
</tbody>
</table>
<!-- Sum : <input type="text" name="total" id="total"/>
Sum-->
<div align="center">
<input type="button" onclick="Sum()" name="Sum" value="Sum" id="sum">
<input id="answer">
</div>
</body>
</html>
The above code generates 9 input number fields in table format to enter numbers and calculate the sum
Add your numbers to an array and loop through. One possible example, see https://codepen.io/anon/pen/yZaBrb:
var a = new Array(1,2,3,4,5,6,7,9,2,4);
var duplicate = false;
for (i=0;i<a.length;i++){
duplicate = false;
for(j=0;j<a.length;j++){
if(i != j && a[i]==a[j])
duplicate = true;
}
if(duplicate)
document.write('<span style="background-color:red;">')
document.write(a[i]);
if(duplicate)
document.write('</span>')
}
Create two events blur & keyup. On blur get the value from the input and push it in an array, on keyup check if the array contains the same value. If the value is present in the array then add a class to the target element or remove it
function Sum() {
alert("hi");
var num1 = Number(document.getElementById("qty1").value);
var num2 = Number(document.getElementById("qty2").value);
var num3 = Number(document.getElementById("qty3").value);
var num4 = Number(document.getElementById("qty4").value);
var num5 = Number(document.getElementById("qty5").value);
var num6 = Number(document.getElementById("qty6").value);
var num7 = Number(document.getElementById("qty7").value);
var num8 = Number(document.getElementById("qty8").value);
var num9 = Number(document.getElementById("qty9").value);
var sum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9
document.getElementById("answer").value = sum;
}
let sumArray = []
document.querySelectorAll('input[type="number"]').forEach((item) => {
item.addEventListener('blur', (e) => {
sumArray.push(e.target.value)
})
item.addEventListener('keyup', (e) => {
if (sumArray.indexOf(e.target.value) !== -1) {
e.target.parentNode.classList.add('error')
} else if (e.target.parentNode.classList.contains('error')) {
e.target.parentNode.classList.remove('error')
}
})
})
table>tbody>tr:nth-child(odd) {
background-color: blue;
}
table>tbody>tr:nth-child(even) {
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(odd) {
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(even) {
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(odd) {
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(even) {
background-color: green;
}
#sumtable th,
#sumtable td {
padding: 5px;
}
.error {
border: 2px solid red;
}
<title>Sum Box</title>
<body>
<table align="center" id="sumtable">
<tbody>
<tr>
<td>
<input type="number" placeholder="input1" value="input1" id="qty1"></td>
<td>
<input type="number" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number" placeholder="input3" value="input3" id="qty3"></td>
</tr>
<tr>
<td><input type="number" placeholder="input4" value="input4" id="qty4"></td>
<td><input type="number" placeholder="input5" value="input5" id="qty5"></td>
<td><input type="number" placeholder="input6" value="input6" id="qty6"></td>
</tr>
<tr>
<td><input type="number" placeholder="input7" value="input7" id="qty7"></td>
<td><input type="number" placeholder="input8" value="input8" id="qty8"></td>
<td><input type="number" placeholder="input9" value="input9" id="qty9"></td>
</tr>
</tbody>
</table>
<!-- Sum : <input type="text" name="total" id="total"/>
Sum-->
<div align="center">
<input type="button" onclick="Sum()" name="Sum" value="Sum" id="sum">
<input id="answer">
</div>
its pretty simple just put same class in input field and loop through it like
In Html ,
<td>
<input type="number" class="checkSame" placeholder="input1" value="input1"id="qty1"></td>
<td>
<input type="number" class="checkSame" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number" class="checkSame" placeholder="input3"value="input3"id="qty3"></td>
then in javascript ,
var inputs = document.getElementsByClassName("checkSame");
var temp;
var count = 1;
for(var i = 0; i < inputs .length; i++)
{
temp = document.getElementsByClassName("checkSame")[i].value;
if(temp == document.getElementsByClassName("checkSame")[count++].value)
{
//change your background color here
break;
}
}
i think it works.
I hope this will help you to find duplicate fields
function Sum() {
alert("hi");
let arr = [];
let sum;
let duplicate = false;
for (let i = 1; i <= 9; i++) {
let num = Number(document.getElementById(`qty${i}`).value);
let indexOfDuplicateNum = arr.indexOf(num);
if (indexOfDuplicateNum > -1){
duplicate = true;
alert('Duplicate value found!');
document.getElementsByTagName('body')[0].style.background = 'red';
document.getElementById(`qty${i}`).classList.add('duplicate-error');
document.getElementById(`qty${indexOfDuplicateNum+1}`).classList.add('duplicate-error');
break;
} else{
//remove error class if value is not duplicate
document.getElementById(`qty${i}`).classList.remove('duplicate-error');
arr.push(num);
sum = arr.reduce((a, b) => a+b, 0);
}
}
if (!duplicate) {
document.getElementById('answer').value = sum;
document.getElementsByTagName('body')[0].style.background = 'white';
}
}
.duplicate-error {
border: 2px solid red;
}
table>tbody>tr:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(odd){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(even){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(even){
background-color: green;
}
#sumtable th, #sumtable td{
padding:5px;
}
<html>
<head>
<title>Sum Calculator</title>
</head>
<title>Sum Box</title>
<body>
<table align="center" id="sumtable">
<tbody>
<tr>
<td>
<input type="number" placeholder="input1" value="input1"id="qty1"></td>
<td>
<input type="number" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number"placeholder="input3"value="input3"id="qty3"></td>
</tr>
<tr>
<td><input type="number" placeholder="input4" value="input4" id="qty4" ></td>
<td><input type="number" placeholder="input5" value="input5" id="qty5" ></td>
<td><input type="number" placeholder="input6" value="input6" id="qty6" ></td>
</tr>
<tr>
<td><input type="number" placeholder="input7" value="input7" id="qty7" ></td>
<td><input type="number" placeholder="input8" value="input8" id="qty8" ></td>
<td><input type="number" placeholder="input9" value="input9" id="qty9" ></td>
</tr>
</tbody>
</table>
<!-- Sum : <input type="text" name="total" id="total"/>
Sum-->
<div align="center">
<input type="button" onclick="Sum()" name="Sum" value="Sum" id="sum">
<input id="answer">
</div>
</body>
</html>

jQuery Dynamic form input validation

This question is based off of another StackOverflow question found here.
My goal is to build simple validation that ensures input fields are filled in sequential order based on their index (natural flow).
» The main complexity is that I'm trying to consolidate validation across different types of input.
» Specifically, radio button groups should be validated as one entity. When using the .prev() and .next() methods, the gender radio group should move to essay or age respectively, not male or female.
» The next bug is that I cannot get the age row to properly disable if the content in any previous row is undone/removed. It does not work consistently and I cannot figure out why.
» The validate button should make items that are filled in green, otherwise highlight them in red color.
If there is a more refined approach to this please feel free to elaborate. If there are easier selectors that I could be utilizes to build up the arrays for more streamlined manipulation and validation, please also enlighten me and share.
Almost Working Example
//StackOverflow Question - https://stackoverflow.com/q/37618826/5076162 [06-03-2016]
//Step 1: Declare the collection of all inputs that should be manipulated.
var $inputFields = $('textarea, input[type="text"], input[type="number"], input[type="radio"]');
//Step 2: Insert the collection into a single array using the .push() method.
var arr = [];
$inputFields.each(function() {
arr.push($(this));
});
//Step 3: Iterate through the newly created array and perform certain functions.
//Source - https://stackoverflow.com/a/5437904/5076162
$.each(arr, function(i) {
if (i > 0) {
$(this).attr('readonly', 'readonly').addClass('disabled');
$(':radio[readonly]:not(:checked)').attr('disabled', true);
//console.log("Iteration number: " + i);
}
});
var $justRadio = $('input[type="radio"]:disabled');
//Step 4: Detect input and apply logic for each situation. Note that different input types require different syntax.
$inputFields.on("propertychange input change focus blur", function(i) {
var index = $inputFields.index(this);
var next = $inputFields.eq(index + 1);
var $checkedRadio = $('input[type="radio"]:checked').length;
var radioCounter = $justRadio.length;
if ($(this).val() === "") {
$inputFields.filter(function() {
return $inputFields.index(this) > index;
}).attr("readonly", true).attr('disabled', true).addClass('disabled');
//console.log('disable Fired');
} else {
next.attr("readonly", false).attr('disabled', false).removeClass('disabled');
$justRadio = $('input[type="radio"]:disabled');
//console.log(radioCounter);
if (radioCounter < 2) {
$justRadio.closest('tr').find($justRadio).attr("readonly", false).attr('disabled', false).removeClass('disabled');
}
}
if ($checkedRadio > 0 && $justRadio.length === 0) {
$inputFields.last().attr("readonly", false).attr('disabled', false).removeClass('disabled');
//console.log("This fired: lastRow");
}
//Step 5: Implement a user interface button so they know they have filled in all fields.
var emptyCount = 0;
$inputFields.not($('input[type="radio"]')).each(function() {
if ($(this).val() === "") {
emptyCount = +1;
}
//console.log("Empty Count: " + emptyCount);
});
var vRCount = 0;
$inputFields.not($('input[type="text"], input[type="number"], textarea')).each(function() {
if ($(this).is(":checked")) {
vRCount = +1;
}
//console.log("Empty Count: " + emptyCount);
});
$('input.validateCheck').on("click", function() {
if (emptyCount === 0 && vRCount > 0) {
$inputFields.closest('tr').find('td').css("color", "green");
$('input.validateCheck').text("Success!").attr("value", "Success!");
}
});
});
table {
border-collapse: collapse;
}
td {
vertical-align: top;
border: solid 1px #ACE;
padding: 2px;
font-family: arial;
}
input {
width: 450px;
text-align: center;
}
textarea {
margin: 0;
width: 448px;
text-align: left;
}
input[type="radio"] {
width: 15px;
}
div.gender {
display: inline-block;
clear: none;
width: 219px;
}
.disabled {
background-color: #f1f1f1;
}
input[type="button"] {
width: 546px;
margin-top: 5px;
color: #FFF;
background-color: red;
border: solid 1px #ACE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form>
<table>
<tr>
<td>First name:</td>
<td>
<input type="text" name="firstname">
</td>
</tr>
<tr>
<td>Last name:</td>
<td>
<input type="text" name="lastname">
</td>
</tr>
<tr>
<td>Essay:</td>
<td>
<textarea rows="4" cols=""></textarea>
</td>
</tr>
<tr>
<td>Gender:</td>
<td>
<div class='gender'>
<input type="radio" name="gender" value="male">Male</div>
<div class='gender'>
<input type="radio" name="gender" value="female">Female</div>
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="number" name="age" min="18" max="99">
</td>
</tr>
</table>
<input class='validateCheck' type="button" value="Validate" />
</form>
Use HTML5 form validations. It is a lot easier and faster. Hope this helps...
<style>
form{font-size:100%;min-width:560px;max-width:620px;width:590px;margin:0 auto;padding:0}
form fieldset{clear:both;font-size:100%;border-color:#000;border-style:solid none none;border-width:1px 0 0;margin:0;padding:10px}
form fieldset legend{font-size:150%;font-weight:400;color:#000;margin:0;padding:0 5px}
label{font-size:100%}
label u{font-style:normal;text-decoration:underline}
input,select,textarea{font-family:Tahoma, Arial, sans-serif;font-size:100%;color:#000}
input:required ,select:required, textarea:required, radio:required{
font-family:Tahoma, Arial, sans-serif;
font-size:100%;
color:#000;
border-color:red;
background: #fff url(images/red-asterisk.png) no-repeat 98% center;
}
input:focus ,select:focus, textarea:focus, radio:focus{
background: #fff url(invalid.png) no-repeat 98% center;
box-shadow: 0 0 5px #d45252;
border-color: #b03535
}
input:valid ,select:valid, textarea:valid, radio:valid{
background: #fff url(valid.png) no-repeat 98% center;
box-shadow: 0 0 5px #5cd053;
border-color: #28921f;
}
:valid {box-shadow: 0 0 5px green}
:-moz-submit-invalid {box-shadow: 0 0 5px pink}
</style>
<form>
<table>
<tr>
<td>First name:</td>
<td>
<input type="text" id="firstname" name="firstname" required>
</td>
</tr>
<tr>
<td>Last name:</td>
<td>
<input type="text" name="lastname" required>
</td>
</tr>
<tr>
<td>Essay:</td>
<td>
<textarea rows="4" cols="20" required></textarea>
</td>
</tr>
<tr>
<td>Gender:</td>
<td>
<div class='gender'>
<input type="radio" name="gender" value="male" required> Male</div>
<div class='gender'>
<input type="radio" name="gender" value="female" required> Female</div>
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="number" name="age" min="18" max="99" required>
</td>
</tr>
</table>
<input class='validateCheck' type="submit" value="Validate" />
</form>

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