How to fix duplicate entries in number field in javascript - 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>

Related

How can I correct this JS function to make it fit for all the cells in the table?

Scenario: I'd like to input the number at the top of the page. Then I press the button "First Line". It will create a new table row with 16 cells, with the numbers inputted displayed in the new cells. When I press another button "New Line", another row of 16 cells will appear below, with some particular numbers coming out in the new cells as I programmed in function newNo().
Question: I know my syntax in the function newNo() and the two var at the bottom of the js file is wrong. I want this function to be applied in all the new cells, so that it will look up the same "column" or the same cell in the 1st row, and produce a series of numbers according to the algorithm in newNo(), and show it in the next row, in each respective cell. Can this function do so in js/html?
Thanks a lot!
const tab = document.getElementById("tab");
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
btn1.addEventListener('click', () => {
let row = tab.insertRow(-1);
for (var i = 0; i <= 15; i++) {
let c = row.insertCell(i);
c.id = `R${row.rowIndex}C${++c.cellIndex}`;
let inpId = 'inp' + (i + 1);
let inpEl = document.getElementById(inpId);
c.innerHTML = inpEl.value;
}
});
function newCells() {
let row = tab.insertRow(-1);
for (var i = 0; i <= 15; i++) {
let c = row.insertCell(i);
c.id = `R${row.rowIndex}C${++c.cellIndex}`;
}
}
btn2.addEventListener('click', () => {
newCells();
newNo();
});
var row1 = [R1C1, R1C2, R1C3, R1C4, R1C5, R1C6, R1C7, R1C8, R1C9, R1C10, R1C11, R1C12, R1C13, R1C14, R1C15, R1C16];
var r1 = document.getElementById(row1).valueAsNumber;
function newNo() {
if (r1 > 0) {
var choices = [0, (R1C1.valueAsNumber) % 7, (R1C1.valueAsNumber + 2) % 7, (R1C1.valueAsNumber - 2) % 7];
var x = Math.floor(Math.random() * choices.length);
if (choices[x] == choices.at(0)) {
R2C1.innerHTML = choices[x];
} else if (choices[x] !== choices.at(0) && choices[x] <= 0) {
R2C1.innerHTML = choices[x] + 7;
}
}
}
th,
tr,
td {
border: 1px solid black;
padding: 5px;
width: 40px;
}
<div id="data">
<table id="inpdata">
<tr>
<td id="inpb1">Group 1</td>
<td id="inpb2">Group 2</td>
<td id="inpb3">Group 3</td>
<td id="inpb4">Group 4</td>
</tr>
<tr>
<td>
<input type="number" id="inp1" title="inp1">
<input type="number" id="inp2" title="inp2">
<input type="number" id="inp3" title="inp3">
<input type="number" id="inp4" title="inp4">
</td>
<td>
<input type="number" id="inp5" title="inp5">
<input type="number" id="inp6" title="inp6">
<input type="number" id="inp7" title="inp7">
<input type="number" id="inp8" title="inp8">
</td>
<td>
<input type="number" id="inp9" title="inp9">
<input type="number" id="inp10" title="inp10">
<input type="number" id="inp11" title="inp11">
<input type="number" id="inp12" title="inp12">
</td>
<td>
<input type="number" id="inp13" title="inp13">
<input type="number" id="inp14" title="inp14">
<input type="number" id="inp15" title="inp15">
<input type="number" id="inp16" title="inp16">
</td>
</tr>
</table>
<br>
<button id="btn1">First Line</button>
<button id="btn2">New Line</button>
</div>
<br>
<div id="tables">
<table id="tab">
<tr>
<th colspan="4">Group 1</th>
<th colspan="4">Group 2</th>
<th colspan="4">Group 3</th>
<th colspan="4">Group 4</th>
</tr>
</table>
</div>

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 '

how to output the minimum value from array on the website

i have the input values and js creates the array. I need that all values should be sorted by values and output the min value on the web page. User should see smth like this: the subject where u get (3(for example)) should be improved in next few days. please guys!
document.querySelector('button').addEventListener('click', function(e) {
var inputs = document.querySelectorAll('input');
var obj = [].reduce.call(inputs, (accumulator, currentValue, currentIndex) => {
accumulator[`val${currentIndex}`] = currentValue.value
return accumulator
}, {})
console.log(obj)
});
<form>
<table id="tblSearchTally">
<tr>
<td>Biology:<input type= "text" ></td>
</tr>
<tr>
<td>Chemistry:<input type= "text" ></td> </tr>
<tr>
<td>Physics:<input type= "text" ></td> </tr>
<tr>
<td>Math:<input type= "text" ></td>
</tr>
</table>
<button type="button">Go</button>
</form>
Details are commented in demo
// Reference the DOM elements
// Get the first <form> on page
const form = document.forms[0];
// Collect all form controls with [name=grade] into a NodeList
const inputs = form.elements.grade;
const minCell = document.querySelector('.MIN');
const maxCell = document.querySelector('.MAX');
// Register the <form> to the click event
form.onclick = calc;
// Event handler passes event object
function calc(e) {
// if clicked tag (ie e.target) is a button tag...
if (e.target.tagName === "BUTTON") {
/*
covert NodeList into an array
create an array of input values
and convert them into Numbers
then return the array of Numbers
in order from least to greatest
*/
let ordered = [...inputs].map(input => Number(input.value)).sort((a, b) => a - b);
console.log(ordered);
// Display the first Number of the Number array
minCell.textContent = ordered[0];
// Display the last Number of the Number array
maxCell.textContent = ordered[ordered.length - 1];
}
}
:root,
body {
font: 700 small-caps 2vw/1.45 Consolas;
}
table,
td {
table-layout: fixed;
border-collapse: collapse;
width: 200px;
border: 1px solid #000
}
td {
padding: 2px;
width: 50%;
text-align: right;
}
tfoot tr:first-of-type td {
text-align: left;
}
tfoot tr:first-of-type td::before {
content: attr(class)': ';
}
caption {
font-size: 1.25rem
}
input {
font: inherit;
text-align: right;
display: block;
width: 85px
}
button {
font: inherit;
text-align: right;
}
.as-console-wrapper {
width: 350px;
min-height: 100%;
margin-left: 45%;
}
<form>
<table>
<caption>Grades</caption>
<tbody>
<tr>
<td>Biology: </td>
<td><input name='grade' type="number" min='0' max='100' value='0'></td>
</tr>
<tr>
<td>Chemistry: </td>
<td><input name='grade' type="number" min='0' max='100' value='0'></td>
</tr>
<tr>
<td>Physics: </td>
<td><input name='grade' type="number" min='0' max='100' value='0'></td>
</tr>
<tr>
<td>Math: </td>
<td><input name='grade' type="number" min='0' max='100' value='0'></td>
</tr>
</tbody>
<tfoot>
<tr>
<td class='MIN'></td>
<td class='MAX'></td>
</tr>
<tr>
<td colspan='2'><button type="button">GO</button></td>
</tr>
</tfoot>
</table>
</form>
Put all the values in an array and use this: Math.min(...name_of_array) ;
Example:
var arr = [4,1,2,0,9,5];
Math.min(...arr) ;
The output will be: 0
create an array of scores, then calculate min value:
const scores = [...inputs].map( x => Number(x.value) );
const min = Math.min( ...scores );
Instead of reduce, you can use map to save inputs value into an array and sort it.
document.querySelector('button').addEventListener('click', function(e) {
var inputs = document.querySelectorAll('input');
var values = [].map.call(inputs, inputEl => inputEl.value);
values.sort();
console.log(values);
});
The minium value is values[0]
you can do like this by using jquery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body>
<form>
<table id="tblSearchTally">
<tr>
<td>Biology:<input type="text" /></td>
</tr>
<tr>
<td>Chemistry:<input type="text" /></td>
</tr>
<tr>
<td>Physics:<input type="text" /></td>
</tr>
<tr>
<td>Math:<input type="text" /></td>
</tr>
</table>
<input type="button" onclick="MinValue('input')" value="Go" />
</form>
<script>
function MinValue(selector) {
var min = null;
$(selector).each(function () {
var value = parseInt(this.value, 0);
if (min === null || value < min) {
min = value;
}
});
console.log(min);
}
</script>

Alert to stop duplicate data

I am trying to add an alert to notify the user that data has already been entered. I want to apply this to the flight number only. So that when a user types in an already typed flight number and saves it into the array it will pop up a message telling them that it has already been posted.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
</style>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</html>
I am also trying to highlight the member table to show which group they are in based on total miles. I would like for the color of the highlight to match the member level. Something kind of like this:
<style>
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
function highlightWeightClass(total-miles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = total-miles< 10000 ? "bronze" : "";
rows[1].className = total-miles >= 10000 && total-miles < 25000 ? "silver" : "";
rows[2].className = total-miles >= 25000 ? "gold" : "";
</script>
For checking if an Array contains on Object, use this:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
For highlighting the member table: add an event listener for document.getElementById("Miles")'s keyup and execute your function then.
<html>
<head>
<title>Member Info</title>
<style>
table, th, td {
border: 1px solid black;
text-align: center;
border-collapse: collapse;
}
.bronze {
background: rgb(80.4, 49.8, 19.6);
}
.silver {
background: silver
}
.gold {
background: gold
}
</style>
<script>
Array.prototype.contains = function(obj) {//function to check if an Array contains an object
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
function highlightWeightClass(totalmiles) {
var rows = document.getElementById("MemberTable").rows;
rows[0].className = totalmiles< 10000 ? "bronze" : "";
rows[1].className = totalmiles >= 10000 && totalmiles < 25000 ? "silver" : "";
rows[2].className = totalmiles >= 25000 ? "gold" : "";
}
</script>
<script type="text/javascript">
var FlightNumber=new Array();
var Miles=new Array();
function insert(){
var FlightNumberValue = document.getElementById('FlightNumber').value;
if(!FlightNumber.contains(FlightNumberValue)){
var MilesValue = document.getElementById('Miles').value;
FlightNumber[FlightNumber.length]=FlightNumberValue;
Miles[Miles.length]=MilesValue;
} else {
alert("You have already entered this flight number.");
}
}
function showFlightNumber() {
var content="<b></b><br>";
for(var i = 0; i < FlightNumber.length; i++) {
content +=FlightNumber[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
function showMiles() {
var content="<b></b><br>";
for(var i = 0; i < Miles.length; i++) {
content +=Miles[i]+"<br>";
}
document.getElementById('display2').innerHTML = content;
// new code
var total=0;
for(var i = 0; i < Miles.length; i++) {
total += Number.parseInt(Miles[i]);
}
document.getElementById('total-miles').innerHTML = total;
}
window.onload = function(){
document.getElementById("Miles").addEventListener("keyup", function(event){
highlightWeightClass(document.getElementById("Miles").value);
});
}
</script>
</head>
<body>
<form id="form">
<h1>Find out what Flight Class Member you are!</h1>
<p>To use, please input the flight number and number of miles. Press save and then show. To enter more than one press "Enter More" button and repeat steps.<p>
<br>
<label for="FlightNumber">Flight Number</label> <input id="FlightNumber" type="text" />
<br>
<label for="Miles">Miles</label><input id="Miles" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show flight number" onclick="showFlightNumber();">
<input type="button" value="Show miles" onclick="showMiles();">
<input type= "reset" value="Enter More" />
<hr>
</form>
<table style="width:100%">
<tr>
<th>Flight Number</th>
<th>Miles</th>
</tr>
<tr>
<td><div id="display">
</div></td>
<td><div id="display2">
</div></td>
</tr>
<td>Total Miles:</td>
<td id="total-miles"></td>
</table>
<br><br>
<table id="MemberTable" style="width:100%", border="1px solid black">
<tr>
<td>Bronze Member</td>
<td><10000 miles flown</td>
</tr>
<tr>
<td>Silver Member</td>
<td><25000 miles flown</td>
</tr>
<tr>
<td>Gold Member</td>
<td>>25000 miles flown</td>
</tr>
</table>
</body>
</html>

Jquery return value from two change functions to calculate

I'm trying to create some calculation script. I have a form with some input fields. One is text and one are multiple radio buttons.
I want to change the price field according to the values which are set.
I got this working when I change the radio buttons in the table. However I'm stuck on how to multiple the value with the value from updateQuantity function. That function only works when I change the radio buttons again.
To make things clear I created a fiddle here.
My HTML
<form action="url" id="product_configure_form" method="post">
<span class="price"></span>
<table id="order" class="order">
...
<tbody>
<tr>
<td>
<input type="radio" id="product_configure_custom_123_456" name="custom[123]" value="somevalue" data-price="99.95">
</td>
</tr>
<tr>
<td>
<input type="radio" id="product_configure_custom_321_654" name="custom[321]" value="somevalue" data-price="199.95">
</td>
</tr>
</tbody>
</table>
<input type="text" name="quantity" value="1" />
<div class="change">
+
-
</div>
</form>
My Script
<script type="text/javascript">
function updateQuantity(way){
var quantity = parseInt($('.cart input').val());
if (way == 'up'){
if (quantity < 50){
quantity++;
} else {
quantity = 50;
}
} else {
if (quantity > 1){
quantity--;
} else {
quantity = 1;
}
}
$('.cart input').val(quantity);
}
function update_amounts() {
var price = $('#order').find('input[type="radio"]:checked').data('price');
var times = $('.cart input').val();
var value = (price * times).toFixed(2);
$('.price').text('€' + value);
}
$(document).ready(function(){
$("#product_configure_form").on("change", "#order input", update_amounts);
$(".cart input").on("change keyup paste", update_amounts);
});
</script>
Call update_amounts() on the end of your updateQuantity() function.
Or change it to this on the same line as I mentioned above:
$('.cart input').val(quantity).change();
Working Demo
function updateQuantity(way) {
var quantity = parseInt($('.cart input').val());
if (way == 'up') {
if (quantity < 50) {
quantity++;
} else {
quantity = 50;
}
} else {
if (quantity > 1) {
quantity--;
} else {
quantity = 1;
}
}
$('.cart input').val(quantity);
update_amounts()
}
function update_amounts() {
var price = $('#order').find('input[type="radio"]:checked').data('price');
var times = $('.cart input').val();
var value = (price * times).toFixed(2);
$('.price').text('€' + value);
}
$(document).ready(function() {
$("#product_configure_form").on("change", "#order input", update_amounts);
$(".cart input").on("change keyup paste", update_amounts);
});
table.order {
margin: 15px 0;
width: 100%;
}
.order th {
background: #eee none repeat scroll 0 0;
padding: 10px;
text-align: left;
}
.order td {
padding: 5px 10px;
}
.price{
background:#000;
color:#fff;
width:100px;
height:100px;
display:block;
text-align:center;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="url" id="product_configure_form" method="post">
<span class="price">bla</span>
<table id="order" class="order">
<thead>
<tr>
<th>title</th>
<th>price</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="radio" id="product_configure_custom_123_456" name="custom[123]" value="123456" data-price="99.95">
<label for="product_configure_custom_123_456">option a</label>
</td>
<td class="prijs">$99.95</td>
<tr>
<td>
<input type="radio" id="product_configure_custom_321_654" name="custom[123]" value="654321" data-price="199.95">
<label for="product_configure_custom_321_654">option b</label>
</td>
<td class="prijs">$199.95</td>
</tr>
</tbody>
</table>
<div class="cart">
<input type="text" name="quantity" value="1" />
<div class="change">
+
-
</div>
</div>
</form>

Categories

Resources