Exclude certain rows while calculating the minimum value - javascript

I have the following table and I need to find the minimum value in that column.
In this case the value is 20.
However, I need to exclude the last 2 part names and use the rest of the values in the cell to calculate the minimum. In that case the minimum value should be 100.
Here is the code i have for calculating the minimum:
function getMin() {
var maximum = 0;
jQuery(".used").each(function() {
$used= jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
maximum = (value > maximum) ? value : maximum;
});
var min = maximum;
jQuery(".used").each(function() {
$used = jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
min = (value < min) ? value : min;
});
jQuery(".minimum").val(min);
}
<div><input type="text" class="minimum" name="minimum" id="minimum" value="" size="5" onchange="getMin();" readonly>cycles</div>
I couldn't find a way to exclude the last 2 values here. The number of rows can also differ and is not fixed so I need to exclude it based on those 2 string values. Any help is appreciated!! Thank you in advance!

Here is a quick and dirty solution. Loop through the parent object of each row, and ignore the value of used if the label (text) is one of those strings.
I also updated the minimum function to use the math.min on an array of values.
function getMin() {
let vals = [];
$(".row").each(function() {
if ($(this).find("label").html() != "Ignore") {
$used = $(this).find(".used").val();
var usedValue = $used.replace(/,/g, "");
vals.push(parseFloat(usedValue));
}
});
let min = Math.min(...vals);
$(".minimum").val(min);
}
getMin();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<label>Ignore</label>
<input type="text" class="used" value=41>
</div>
<div class="row">
<label>Keep</label>
<input type="text" class="used" value=222>
</div>
<div class="row">
<label>Keep</label>
<input type="text" class="used" value=200>
</div>
<div><input type="text" class="minimum" name="minimum" id="minimum" value="" size="5" onchange="" readonly>cycles</div>

I would mark these different rows in HTML somehow, let's say with excluded class. Hardcoding the labels in JavaScript asks for trouble.
Here's an example, using excluded class for these two last <tr>:
const min = Math.min(...$(':not(.excluded) .used').map(function () {
return Number($(this).val());
}).get());

You could do it like this: Exclude in your each() function every <tr> that has a first column that contains any of the 2 strings you want to exclude:
function getMin() {
var maximum = 0;
jQuery(".used").each(function() {
$used = jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
maximum = (value > maximum) ? value : maximum;
});
var min = maximum;
jQuery("tr").each(function() {
var check = jQuery(this).find("td:nth-child(1)").text();
if (!check.includes("Fan Blade") && !check.includes("Annulus Filler"))
{
$used = jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
min = (value < min) ? value : min;
}
});
jQuery(".minimum").val(min);
}
getMin();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td></td>
<td></td>
<td><input class="used" value="100" /></td>
</tr>
<tr>
<td>Fan Blade (26 off)</td>
<td></td>
<td><input class="used" value="50" /></td>
</tr>
<tr>
<td>Annulus Filler (26 off)</td>
<td></td>
<td><input class="used" value="50" /></td>
</tr>
</table>
<div><input type="text" class="minimum" name="minimum" id="minimum" value="" size="5" onchange="getMin();" readonly>cycles</div>

Related

Calculating value of checkboxes with JavaScript

I need to calculate the values of items in an HTML form using checkboxes. Each checkbox is related to a product serial number, and each checkbox in the form has a different points value. I can't allow the sum of the values to be greater than a predetermined number. I found this JavaScript, which calculates the sum, but when I use it in a form, I can't parse the actual item number. Instead, the form returns the value of a checkbox.
Here is the JavaScript:
<script type="text/javascript">
function chkcontrol(j) {
var sum=0;
for(var i=0; i < document.form1.ckb.length; i++){
if(document.form1.ckb[i].checked){
sum = sum + parseInt(document.form1.ckb[i].value);
}
document.getElementById("msg").innerHTML="Sum :"+ sum;
if(sum >500){
sum = sum - parseInt(document.form1.ckb[j].value);
document.form1.ckb[j].checked = false ;
alert("Sum of the selection can't be more than 500")
//return false;
}
document.getElementById("msg").innerHTML="Sum :"+ sum;
}
}
</script>
And the table looks like this:
<form name=form1 method=post action=check.php>
<table class='table table-striped'>
<tr><th>Select</th></tr>
<tr><td><input type=checkbox name=ckb value=120 onclick='chkcontrol(0)';> Serial# 123001 (value = 120) </td></tr>
<tr><td><input type=checkbox name=ckb value=200 onclick='chkcontrol(1)';> Serial# 123002 - (value = 200) </td></tr>
<tr><td><input type=checkbox name=ckb value=350 onclick='chkcontrol(2)';> Serial# 123003 - (value = 350) </td></tr>
<tr><td><input type=checkbox name=ckb value=100 onclick='chkcontrol(3)';> Serial# 123004 - (value = 100) </td></tr>
</table></form>
Sum of the values can't exceed 500.
<br><br>
<div id=msg></div>
Currently, the value of the checkbox is the number that is added to the sum. When I parse the form, I can only get that number via the name cab and I don't get any information about the Serial#. What I need is to be able to have the value of the checkbox be equal to a serial number of the item - i.e. 123004 - and I can later reference this serial number in a database.
Thanks in advance.
You can create a data attribute for each of the checkbox and add the serial number. Then on execution of the function use document.querySelectorAll to get all the checked checkbox.
document.querySelectorAll will give a nodelist. To use the array method map it is first converted to array using spread operator .... Array method map is used here to return an array of the serial numbers which is retrieved from data attribute
function chkcontrol(j) {
var sum = 0;
const checkedBoxes = []
for (var i = 0; i < document.form1.ckb.length; i++) {
if (document.form1.ckb[i].checked) {
sum = sum + parseInt(document.form1.ckb[i].value);
}
document.getElementById("msg").innerHTML = "Sum :" + sum;
if (sum > 500) {
sum = sum - parseInt(document.form1.ckb[j].value);
document.form1.ckb[j].checked = false;
alert("The total points used can't be more than 500")
//return false;
}
remaining = 500 - sum;
document.getElementById("msg").innerHTML = "<b>Points Used: </b>" + sum + "<br><b>Remaining Points: </b>" + remaining;
}
// added code here
const box = [...document.querySelector('form[name="form1"]')
.querySelectorAll('input[name="ckb"]:checked')]
.map(item => item.dataset.serial);
console.log(box)
}
<form name='form1'>
<table>
<tr>
<th>Select</th>
</tr>
<tr>
<td><input type='checkbox' name='ckb' data-serial='123001' value='120' onclick='chkcontrol(0)' ;> Serial# 123001 (value = 120) </td>
</tr>
<tr>
<td><input type='checkbox' name='ckb' data-serial='123002' value='200' onclick='chkcontrol(1)' ;> Serial# 123002 - (value = 200) </td>
</tr>
<tr>
<td><input type='checkbox' name='ckb' data-serial='123003' value='350' onclick='chkcontrol(2)' ;> Serial# 123003 - (value = 350) </td>
</tr>
<tr>
<td><input type='checkbox' name='ckb' data-serial='123004' value='100' onclick='chkcontrol(3)' ;> Serial# 123004 - (value = 100) </td>
</tr>
</table>
</form>
<div id='msg'></div>
will you try that... ?
const
myForm = document.forms['my-forn']
ckb_n = ['ckb1', 'ckb2', 'ckb3', 'ckb4' ]
, pSum = document.querySelector('#p-sum span')
;
myForm.onsubmit = e =>
{
e.preventDefault() // disable submit for test
}
myForm.oninput = e =>
{
let total = ckb_n.reduce((sum,nam)=>
{
sum += myForm[nam].checked ? Number(myForm[nam].value) : 0
return sum
}
, 0)
if (total > 500)
{
e.target.checked = false
let label = e.target.closest('label')
label.classList.add('errarum')
setTimeout(_=>{label.classList.remove('errarum')}, 2000)
alert("Sum of the selection can't be more than 500")
}
else
pSum.textContent = total
}
label {
display : block;
cursor : pointer;
}
.errarum {
color : red;
}
<form name="my-forn">
<label>
<input type="checkbox" name="ckb1" value="120" >
Serial# 123001 (value = 120)
</label>
<label>
<input type="checkbox" name="ckb2" value="200" >
Serial# 123002 (value = 200)
</label>
<label>
<input type="checkbox" name="ckb3" value="350" >
Serial# 123003 (value = 350)
</label>
<label>
<input type="checkbox" name="ckb4" value="100" >
Serial# 123004 (value = 100)
</label>
</form>
<p id="p-sum"> Sum : <span>0</span><p>

percentages when converting sterling to euro

Hi I am trying to convert Sterling to Euros. But I can't seem to get the percentages correct. I have tried it several ways without luck. The idea is to get 1% of the sterling price then multiply it by the conversion rate and add it to the sterling price to make the euro total, and then do the same with vat.
Hope someone can help, thanks!
Here is my code.
var input = document.querySelectorAll('input');
var conversionRate = input[0];
var sterling = input[1];
var vat = input[2];
var euro = input[3];
init();
function init() {
calculateKeyUp();
}
function calculateKeyUp() {
for (var i = 0; i < input.length; i++) {
input[i].addEventListener("keyup", function() {
//var totalLessVat = (sterling.value) + (conversionRate.value * (sterling.value / 100));
var sterling1Per = sterling.value / 100;
var convert = sterling1Per * conversionRate.value;
var totalLessVat = convert + sterling.value;
//var total = (totalLessVat) + (vat.value * (totalLessVat / 100));
var euro1Per = totalLessVat / 100;
var addVat = euro1Per * vat.value;
var total = addVat + totalLessVat;
euro.value = Math.floor(total);
});
}
}
<div id="calculator-form">
<table>
<tr>
<td>Conversion Rate: </td>
<td><input type="number" id="conversionRate"> %</td>
</tr>
<tr>
<td>Sterling Price: </td>
<td><input type="number" id="sterling"> £</td>
</tr>
<tr>
<td>Vat: </td>
<td><input type="number" id="vat"> %</td>
</tr>
<tr>
<td>Euro Price is </td>
<td><input type="number" id="euro" disabled> €</td>
</tr>
</table>
</div>
The .value of an input is going to be a String, so you will need to parse the number out of each input you are working with. If it's an int you can use:
var sterling1Per = parseInt(sterling.value, 10) / 100;
If it's a float, you can use:
var sterling1Per = parseFloat(sterling.value) / 100;
Anywhere that you use an input .value that needs to be a number needs to be parsed accordingly

Jquery: calculate volume

Took the base of a code from one user and modified a bit. Basically it does what i need - calculates the sum from three values (first two are in meters, third in centemeters). but i would like it to be more simpler. I dont't need "select options" in thickness field - it must be calculated in centemeters!.
And second request - the amount must be in m3!
html:
<table>
<tbody>
<tr>
<td>Width (m)</td>
<td>
<input type="text" id="width" />
</td>
</tr>
<tr>
<td>Length (m)</td>
<td>
<input type="text" id="length" />
</td>
</tr>
<tr>
<td>Thickness (cm)</td>
<td>
<input type="text" id="thickness" />
</td>
<td>
<select id="sel">
<option>centemeter</option>
<option>meter</option>
<option>melemeter</option>
</select>
</td>
</tr>
<tr>
<td>Total (m<sup>3</sup>)</td>
<td id="answer"></td>
</tr>
</tbody>
</table>
javascript:
$("#width ,#length ,#thickness, #sel").on('change keyup keydown', function() {
var width = $("#width").val();
var length = $("#length").val();
var thickness = $("#thickness").val();
var result = width * length * thickness;
var select_val = $("#sel").val();
if (select_val == "centemeter") {
$("#answer").text(result).append(" cm<sup>3</sup>");;
} else if (select_val == "meter") {
result = result / 100;
$("#answer").text(result).append(" m<sup>3</sup>");;
} else if (select_val == "melemeter") {
result = result * 10;
$("#answer").text(result).append(" mm<sup>3</sup>");
}
});
jsfiddle
update: i thought this will be an easy task: calculate amount of three numbers - something like var result = width * length * thickness; only thickness is 1/100 of width and length...
below solution to my answer. wasn't that complicated, is it?
$("#width ,#length ,#thickness").on('change keyup keydown', function () {
var width = $("#width").val();
var length = $("#length").val();
var thickness = $("#thickness").val();
var result = width * length * thickness;
result = result/100;
$("#answer").text(result).append(" m<sup>3</sup>");;
});
jsfiddle

Javascript - Insert code segments at multiple locations

What I like to do is: If any of the 3 optional fields is filled out, a chunk of code(row) will be inserted into the source code(table) and then the entire code will be outputted.
My issue right now is: If more than one of the fields is entered, only the last input is inserted. I need all of them inserted. I suspect that the "code =" statement needs to be changed/relocated but not sure how to go about it. I'm a beginner in javascript, so please keep your answers as basic as you can. Thank you!!
html:
<input id="input1" onChange="update()">
<input id="input2" onChange="update()">
<input id="input3" onChange="update()">
javascript:
var source = '<table><!--PlaceHolder1--><!--PlaceHolder2--><!--PlaceHolder3--></table>';
var insert = '<tr><td>InsertText</td></tr>';
function update(){
if(document.getElementById("input1").value != ""){
var x = document.getElementById("input1").value;
var y = insert.replace("InsertText", x );
code = source.replace("<!--PlaceHolder1-->", y );
}
if(document.getElementById("input2").value != ""){
var x = document.getElementById("input2").value;
var y = insert.replace("InsertText", x );
code = source.replace("<!--PlaceHolder2-->", y );
}
if(document.getElementById("input3").value != ""){
var x = document.getElementById("input3").value;
var y = insert.replace("InsertText", x );
code = source.replace("<!--PlaceHolder3-->", y );
}
}
document.write(code);
It looks like you're losing the result of the first replace, which is in the variable "code" because you're overwriting it with the contents of "source" on subsequent replaces.
Instead of this:
code = source.replace("<!--PlaceHolder2-->", y );
Try this:
code = code.replace("<!--PlaceHolder2-->", y );
And I think you'll get what you're expecting.
Part of the problem is that you're trying to do this with string replacement. You should be using proper DOM manipulation. This will also allow you to clean up your code a lot:
window.onload = function() {
function update(e) {
var target = e.target,
num = target.getAttribute("data-num"),
td = document.querySelectorAll("#theTable td")[num - 1];
td.textContent = target.value;
td.parentNode.style.display = "table-row";
}
for (var i = 1; i <= 3; i += 1) {
document.getElementById("input" + i).onchange = update;
}
}
#theTable tr {
display: none;
}
<input id="input1" data-num="1">
<input id="input2" data-num="2">
<input id="input3" data-num="3">
<table id="theTable">
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
</table>

adding table values in javascript is giving me a result in the table cell of NaN

I am getting a result of NaN in my total table cell value. I am adding two total cells that are being calculated by each time the user enters in the quantity. I am trying to figure out and understand why I am getting this result. This is the code for the function that has the calculation in it.
<html>
<head>
<title> Cart </title>
<h1> My cart </h1>
<script type = "text/javascript">
function retr()
{
var cke = document.cookie;
var tot1 = document.getElementById("t1").value;
var tot2 = document.getElementById("t2").value;
if (cke.length>0) {
start = cke.indexOf("Circle=");
if (start!= -1) {
start = start + 7
end = cke.indexOf("$", start);
if (end == -1) end = cke.length;
qu1 = cke.substring(start, end);
document.getElementById("q1").value = qu1;
}
}
if (cke.length>0) {
start1 = cke.indexOf("$");
if (start1!= -1) {
start1 = start1 + 0
end = cke.indexOf("e", start1);
if (end == -1) end = cke.length;
pr1 = cke.substring(start1, end);
document.getElementById("p1").value = pr1;
}
}
document.getElementById("t1").value = parseFloat(qu1) * parseFloat(pr1);
if (cke.length>0) {
start = cke.indexOf("Stickman=");
if (start!= -1) {
start = start + 9
end = cke.indexOf("$", start);
if (end == -1) end = cke.length;
qu2 = cke.substring(start, end);
document.getElementById("q2").value = qu2;
}
}
if (cke.length>0) {
start = cke.indexOf("$");
if (start!= -1) {
start = start + 54
end = cke.indexOf("e", start);
if (end == -1) end = cke.length;
pr2 = cke.substring(start, end);
document.getElementById("p2").value = pr2;
}
}
alert(qu1);
alert(pr1);
alert(qu2);
alert(pr2);
alert(t2);
document.getElementById("t2").value = parseFloat(qu2) * parseFloat(pr2);
document.getElementById("tot").value = parseFloat(tot1) + parseFloat(tot2);
document.getElementById("ret").value = cke;
}
</script>
</head>
<body onload = "retr()">
<table border = "1">
<td>Circle </td>
<td><input type = "text" size = "8" id = "q1" readonly = "readonly" /></td>
<td> <input type = "text" size = "8" id = "p1" readonly = "readonly" /> </td>
<td> <input type = "text" size = "8" id ="t1"> </td>
<tr> </tr>
<td> Stickman </td>
<td> <input type = "text" size = "8" id = "q2" readonly = "readonly" /></td>
<td> <input type = "text" size = "8" id = "p2" readonly = "readonly" /> </td>
<td> <input type = "text" size = "8" id = "t2" > </td>
<tr> </tr>
<td colspan = "3"> TOTAL:</td>
<td> <input type = "text" size = "8" id = "tot"> </td>
</table>
<br /> <br />
<input type ="text" id = "ret" readonly = "readonly" />
<br / > <br />
<input type = "button" value = "Checkout">
<br /> <br />
<a href = "store.html" > Continue Shopping </a>
</body>
</html>
Ok, so assuming your cookie looks like this:
"Circle=123$456e; Stickman=123$456e"
I have fixed your code to run. Here is a working example:
jsfiddle example
You have several issues in your code, the main points:
You kept the "$" sign which is not a number therefore you got the
NaN
You did not set the variables tot1 and tot2 after they were
filled, or at least you did not provide default values.
While searching for the 2nd price you did not use the start1 position of the last "$" sign as a starting point. therefore you ended up at the wrong price.
Are you familiar with the JavaScript value: Not-a-Number (NaN)? It sounds like some user entered value is generating a result that is basically an illegal number.

Categories

Resources