checkbox logic not working correctly - javascript

I have the following form, with several checkboxes. Each set of checkboxes works fine, but when you change an input in the other set of checkboxes, it no longer filters based on the first set (and vice versa).
I need the logic from each set to crossover, and not sure how to achieve that?
$(document).ready(function() {
$("#type :checkbox").click(function() {
$("td").parent().hide();
$("#type :checkbox:checked").each(function() {
$("." + $(this).val()).parent().show();
});
});
$("#fee :checkbox").click(function() {
$("td").parent().hide();
$("#fee :checkbox:checked").each(function() {
$("." + $(this).val()).parent().show();
});
});
});
var repayment = function() {
};
window.onload = function() {
document.repaymentcalc.homevalue.onchange = repayment;
document.repaymentcalc.loanamount.onchange = repayment;
document.repaymentcalc.numberpayments.onchange = function() {
$('#years').html(this.value + ' years');
};
makeSomething();
};
function makeSomething() {
$('tbody tr').each(function(idx, row) {
var $row = $(row);
var initialRateCell = $row.find('td')[2];
var repaymentCell = $row.find('td').last()
var rate = parseFloat($(initialRateCell).html());
var repaymentVal = computeRepayment(rate);
$(repaymentCell).html(repaymentVal.repayment);
});
}
$("#myForm :input").change(function() {
makeSomething();
});
function computeRepayment(rate) {
var x = parseInt(document.repaymentcalc.loanamount.value, 10);
var y = parseInt(rate * 100, 10) / 120000;
var z = parseInt(document.repaymentcalc.numberpayments.value, 10) * 12;
var h = parseInt(document.repaymentcalc.homevalue.value, 10);
var repayment = y * x * Math.pow((1 + y), z) / (Math.pow((1 + y), z) - 1);
var loantovalue = x / h * 100;
var year = z / 12;
return {
repayment: repayment.toFixed(2),
loantovalue: loantovalue,
year: year
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section id="type">
<p id="Mortgage Type">Mortgage Type</p>
<input type="checkbox" name="type" value="t2" id="t2" />2yr Fixed
<br>
<input type="checkbox" name="type" value="t3" id="t3" />3yr Fixed
<br>
<input type="checkbox" name="type" value="t5" id="t5" />5yr Fixed
<br>
<input type="checkbox" name="type" value="t9" id="t9" />Tracker
<br>
<input type="checkbox" name="type" value="t1" id="t1" checked/>All
<br>
</section>
<section id="fee">
<p id="Fee">Fee</p>
<input type="checkbox" name="fee" value="f2" id="f2" />Fee
<br>
<input type="checkbox" name="fee" value="f3" id="f3" />No Fee
<br>
<input type="checkbox" name="fee" value="f1" id="f1" checked/>All
<br>
</section>
<form name="repaymentcalc" id="myForm" action="">
</br>
<p>
Home Value £
<input type="number" id="homevalue" value="250000" style="width: 75px">
</p>
<p>
Loan Amount £
<input type="number" id="loanamount" value="200000" style="width: 75px">
</p>
Term
<input type="range" id="numberpayments" value="25" min="1" max="40" style="width: 100px">
<div id="years" style="display:inline-block;">25 years</div>
<p>
<div id="ltv">Loan to Value: 80.0%</div>
</div>
</form>
<br>
<div id="mortgagediv">
<table id="mortgagetable">
<thead>
<tr class="productheader">
<th class="lender">Lender</th>
<th class="type">Type</th>
<th class="inititalrate">Initial Rate (%)</th>
<th class="svr">SVR (%)</th>
<th class="apr">Overall APR (%)</th>
<th class="fee">Fee (£)</th>
<th class="ltv">LTV (%)</th>
<th class="repayment">Monthly Repayment (£)</th>
</tr>
</thead>
<tbody>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t2">2yr Fixed</td>
<td class="tg-031e">1.64</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f3"></td>
<td class="tg-031e">70</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t3">3yr Fixed</td>
<td class="tg-031e">1.69</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f3"></td>
<td class="tg-031e">75</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t5">5yr Fixed</td>
<td class="tg-031e">1.79</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f3"></td>
<td class="tg-031e">80</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t9">Tracker</td>
<td class="tg-031e">1.64</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f3"></td>
<td class="tg-031e">70</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t2">2yr Fixed</td>
<td class="tg-031e">1.69</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f2">999</td>
<td class="tg-031e">75</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t3">3yr Fixed</td>
<td class="tg-031e">1.79</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f2">999</td>
<td class="tg-031e">80</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t5">5yr Fixed</td>
<td class="tg-031e">1.79</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f2">999</td>
<td class="tg-031e">80</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t9">Tracker</td>
<td class="tg-031e">1.79</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f2">999</td>
<td class="tg-031e">80</td>
<td class="tg-031e"></td>
</tr>
</tbody>
</table>
</div>

I combined the logic of the two sets into a single callback. It is neither elegant nor efficient, but works.
$(document).ready(function() {
$(":checkbox").click(function() {
$("td").parent().hide();
var selections = [];
$(":checkbox:checked").each(function() {
selections.push("."+$(this).val());
});
$(".product").each(function() {
showRow = true;
for(i=0; i<selections.length; i++){
if (!$(this).children(selections[i]).length){
showRow = false;
}
}
if (showRow) $(this).show();
});
});
});
Here is a demo of it.

You have the event handler on the myform area only
$("#myForm :input").change(function() {
makeSomething();
});
But sections fee and type are outside the form and their change events are never cauth. So, you will need to either move the sections type and fee inside the form myform so they are selected within $("#myForm :input") or add another event handler for the checkboxes.
$("#fee :checkbox").change(function() {
makeSomething();
});
$("#type :checkbox").change(function() {
makeSomething();
});
Check out this fiddle
https://jsfiddle.net/bocanegra_carlos/obcux0d8/

Basically, I think your function should go back to the drawing board when it comes to how you are reading the checkboxes. It can be massively simplified, or at least made more understandable by doing this:
// Store all active classes in this variable
var allActive = [];
// Run this function anytime something changes
function activateClasses(){
// Create a string that jquery can use to search for all the children
var activeClassesString = '.' + allActive.join(', .');
// Instead of looking through _all_ the td elements,
// only look through the parent and search in them.
$('tbody tr').each(function(){
var data = $(this);
// instead of hiding all before, just hide when it finds
// no children with the classes you want
if(allActive.length && !data.find(activeClassesString).length)
data.hide();
// otherwise, show
else
data.show();
});
}
// When your checkbox changes, add the value of it either to the
// array of classes you want to sort, or remove it from the array
$('input[type="checkbox"]').change(function(){
var value = $(this).val();
var index = allActive.indexOf(value);
var checked = $(this).is(':checked');
if(!checked && index > -1)
allActive = allActive.slice(index, 1);
else if(checked && index === -1)
allActive.push(value);
activateClasses();
});
$(document).ready(function() {
var allActive = [];
function activateClasses(){
var activeClassesString = '.' + allActive.join(', .');
$('tbody tr').each(function(){
var data = $(this);
if(allActive.length && !data.find(activeClassesString).length) data.hide();
else data.show();
});
}
$('input[type="checkbox"]').change(function(){
var value = $(this).val();
var index = allActive.indexOf(value);
var checked = $(this).is(':checked');
if(!checked && index > -1)
allActive = allActive.slice(index, 1);
else if(checked && index === -1)
allActive.push(value);
activateClasses();
});
});
var repayment = function() {
};
window.onload = function() {
document.repaymentcalc.homevalue.onchange = repayment;
document.repaymentcalc.loanamount.onchange = repayment;
document.repaymentcalc.numberpayments.onchange = function() {
$('#years').html(this.value + ' years');
};
makeSomething();
};
function makeSomething() {
$('tbody tr').each(function(idx, row) {
var $row = $(row);
var initialRateCell = $row.find('td')[2];
var repaymentCell = $row.find('td').last()
var rate = parseFloat($(initialRateCell).html());
var repaymentVal = computeRepayment(rate);
$(repaymentCell).html(repaymentVal.repayment);
});
}
$("#myForm :input").change(function() {
makeSomething();
});
function computeRepayment(rate) {
var x = parseInt(document.repaymentcalc.loanamount.value, 10);
var y = parseInt(rate * 100, 10) / 120000;
var z = parseInt(document.repaymentcalc.numberpayments.value, 10) * 12;
var h = parseInt(document.repaymentcalc.homevalue.value, 10);
var repayment = y * x * Math.pow((1 + y), z) / (Math.pow((1 + y), z) - 1);
var loantovalue = x / h * 100;
var year = z / 12;
return {
repayment: repayment.toFixed(2),
loantovalue: loantovalue,
year: year
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section id="type">
<p id="Mortgage Type">Mortgage Type</p>
<input type="checkbox" name="type" value="t2" id="t2" />2yr Fixed
<br>
<input type="checkbox" name="type" value="t3" id="t3" />3yr Fixed
<br>
<input type="checkbox" name="type" value="t5" id="t5" />5yr Fixed
<br>
<input type="checkbox" name="type" value="t9" id="t9" />Tracker
<br>
<input type="checkbox" name="type" value="t1" id="t1" checked/>All
<br>
</section>
<section id="fee">
<p id="Fee">Fee</p>
<input type="checkbox" name="fee" value="f2" id="f2" />Fee
<br>
<input type="checkbox" name="fee" value="f3" id="f3" />No Fee
<br>
<input type="checkbox" name="fee" value="f1" id="f1" checked/>All
<br>
</section>
<form name="repaymentcalc" id="myForm" action="">
</br>
<p>
Home Value £
<input type="number" id="homevalue" value="250000" style="width: 75px">
</p>
<p>
Loan Amount £
<input type="number" id="loanamount" value="200000" style="width: 75px">
</p>
Term
<input type="range" id="numberpayments" value="25" min="1" max="40" style="width: 100px">
<div id="years" style="display:inline-block;">25 years</div>
<p>
<div id="ltv">Loan to Value: 80.0%</div>
</div>
</form>
<br>
<div id="mortgagediv">
<table id="mortgagetable">
<thead>
<tr class="productheader">
<th class="lender">Lender</th>
<th class="type">Type</th>
<th class="inititalrate">Initial Rate (%)</th>
<th class="svr">SVR (%)</th>
<th class="apr">Overall APR (%)</th>
<th class="fee">Fee (£)</th>
<th class="ltv">LTV (%)</th>
<th class="repayment">Monthly Repayment (£)</th>
</tr>
</thead>
<tbody>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t2">2yr Fixed</td>
<td class="tg-031e">1.64</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f3"></td>
<td class="tg-031e">70</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t3">3yr Fixed</td>
<td class="tg-031e">1.69</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f3"></td>
<td class="tg-031e">75</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t5">5yr Fixed</td>
<td class="tg-031e">1.79</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f3"></td>
<td class="tg-031e">80</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t9">Tracker</td>
<td class="tg-031e">1.64</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f3"></td>
<td class="tg-031e">70</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t2">2yr Fixed</td>
<td class="tg-031e">1.69</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f2">999</td>
<td class="tg-031e">75</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t3">3yr Fixed</td>
<td class="tg-031e">1.79</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f2">999</td>
<td class="tg-031e">80</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t5">5yr Fixed</td>
<td class="tg-031e">1.79</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f2">999</td>
<td class="tg-031e">80</td>
<td class="tg-031e"></td>
</tr>
<tr class="product">
<td class="tg-031e">Nationwide</td>
<td class="t1 t9">Tracker</td>
<td class="tg-031e">1.79</td>
<td class="tg-031e">3.99</td>
<td class="tg-031e">3.40</td>
<td class="f1 f2">999</td>
<td class="tg-031e">80</td>
<td class="tg-031e"></td>
</tr>
</tbody>
</table>
</div>
Make better use of variables as well, as your code is very heavy. For example, instead of letting jQuery compile a list of all the tds in your document every time, assign it to a global variable. If td should be added dynamically, only update this global variable when new ones are added. That means the jQuery object already exists and there is no time involved in recompiling it, speeding up your code. At the moment that makes little difference, but once your list becomes long enough you will feel some slowdown. I'm also very sure that classes are maybe not your best option here. Maybe data- attributes are better suited, so your tr looks like this:
<tr data-lender="nationwide" data-type="2-years-fixed" data-rate="1.64" data-svr="1.5" /* ... and so on ...*/ ></tr>
The reason you'd want to do that is because this is much more legible than your arbitrary classes - you will get lost in the arbitrary classes you used as they are in no way obvious. Which is more obvious: 'show me a lender with tg-031e f1 f2' or 'Show me a lender with 2-years-fixed type'? (I know its not correct, they aren't saying the same thing, but that's only because I am already getting lost in the technical terms.) Think of the developer that might come after you, and the headache you will be creating. Don't be afraid to use a couple more characters if it makes things more obvious to read, as it will save you a boatload of time in the long run.

Related

How to ADD 2 Tax items in an Invoice after Sub-Total to add up in Total by Javascript

This is my Html code in my Invoice file:
<tr class="item-row">
<td>7.</td>
<td class="item-name">
<input type="text" name="i7_n" placeholder="Enter Item" required="required">
</td>
<td class="description">
<textarea name="i7_d" placeholder="Item Note" class="form-control"></textarea>
</td>
<td>
<input type="number" name="i7_q" step="1" min="0" class="qty">
</td>
<td>
<input type="number" name="i7_c" step="1" min="0" class="cost">
</td>
<td><span class="price">0.00</span></td>
</tr>
<tr>
<td colspan="3" class="blank"></td>
<td colspan="2" class="total-line">Subtotal Rs.</td>
<td td class="total-value"><div id="subtotal">0.00</div></td>
</tr>
<tr>
<td colspan="3" class="blank"></td>
<td colspan="2" class="total-line">CGST 2.5%</td>
<td class="total-value"><textarea id="cgst" placeholder="%">0.00</textarea></td>
</tr>
<tr>
<td colspan="3" class="blank"></td>
<td colspan="2" class="total-line">SGST 2.5%</td>
<td class="total-value"><textarea id="sgst" placeholder="%">0.00</textarea></td>
</tr>
<tr>
<td colspan="3" class="blank"></td>
<td colspan="2" class="total-line">Amount after GST </td>
<td class="total-value"><div id="total">0.00</div></td>
</tr>
<tr>
<td colspan="3" class="blank"></td>
<td colspan="2" class="total-line">Amount Paid Rs.</td>
<td class="total-value"><textarea id="paid">0.00</textarea></td>
</tr>
<tr>
<td colspan="3" class="blank"></td>
<td colspan="2" class="total-line balance">Balance Due Rs.</td>
<td class="total-value balance"><div class="due">875.00</div></td>
</tr>
When i run my this following JS Code:-
//This Updates subtotal & total
function update_total() {
var total = 0;
$('.price').each(function(i){
price = $(this).html().replace("$","");
if (!isNaN(price)) total += Number(price);
});
total = roundNumber(total,2);
$('#subtotal').html(total);
// $('#total').html(total);
update_gst();
}
//this adds CGST & SGST in subtotal
function update_gst() {
var total = $("#subtotal").html().replace("$","") + $("#cgst").val().replace("$","") + $("#sgst").val().replace("$","");
total = roundNumber(total,2) ;
$('#total').html(total);
update_balance();
}
//this updates amount paid & outstanding at end
function update_balance() {
var due = $("#total").html().replace("$","") - $("#paid").val().replace("$","");
due = roundNumber(due,2);
$('.due').html(due);
}
//This updates item Qty * Item Price = Item Total
function update_price() {
var row = $(this).parents('.item-row');
var price = row.find('.cost').val().replace("$","") * row.find('.qty').val();
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html(price);
update_total();
}
This gives me my all balances Ok. My problem is I want to add 2 Taxes (CGST #2.5% & SGST #2.5%) [By using JS only] to Sub-Total to give Final Figures after taxes. . i think my code "update_gst()" has some issues.
Please Help me on how I can update my above JS code...

Javascript XPath table loop td's

I am trying to create a Chrome Extension that will extract some data from a table. I want to transform the TD's of the TR's in simple lines with each column separated by a pipe | character, ex:
01/01/2020 | XX | 57,43 | |
02/01/2020 | YY | 11,22 | |
Here is a part of it:
<table width="100%" border="0" cellpadding="2" cellspacing="0">
<tbody>
<tr>
<td class="TRNbarratabelac" width="3%">
<input type="checkbox" name="chkTodos" id="chkTodos" onclick="selTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNbarratabelac">Data do <br>pagamento</td>
<td class="TRNbarratabelac">Tipo</td>
<td class="TRNbarratabelac">Favorecido/beneficiário</td>
<td class="TRNbarratabelac">Valor (R$)</td>
<td class="TRNbarratabelac">Informações complementares</td>
<td class="TRNbarratabelac" colspan="2" width="20%">Opções</td>
</tr>
<tr>
<td class="TRNlicbe"><input type="checkbox" name="chkSel" id="chkSel" value="1" onclick="verSelTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNlicbe">21/02/2020 </td>
<td class="TRNliebe">Concessionárias</td>
<td class="TRNliebe"> </td>
<td class="TRNlidbe">57,43 </td>
<td class="TRNlicbe"> </td>
<td class="TRNlicbde" width="8%">Visualizar</td>
<td class="TRNlicbde" width="12%"><span>enviar por email</span> </td>
</tr>
</tbody>
</table>
To iterate over it, I use XPath like this:
function DOMtoString(doc) {
let path_tr = '(//div[#class="contborda"])[4]/table[3]/tbody/tr[position()>1]';
var tr = doc.evaluate(path_tr, doc, null, XPathResult.ANY_TYPE, null);
let alertText = '';
let x = tr.iterateNext();
while (x) {
alertText += x.textContent;
x = tr.iterateNext();
}
return alertText;
}
Here I get the table (ignoring the first TR with column names), but the result is this (just some part of it):
<br> <br> 21/02/2020 <br> Concessionárias<br> <br> 57,43 <br> <br> Visualizar<br> enviar por email <br><br>
I see that XPath is adding BR's on it.
I try to loop over the TD's of these TR's with no success like this:
let path_td = '//td';
var td = tr.evaluate(path_td, tr, null, XPathResult.ANY_TYPE, null);
What is the correct way that I can interact over the TD's and get the raw text of them with no BR's?
Use innerText instead of textContent to avoid line breaks. You can use Document.querySelector() instead of XPath which will make DOM manipulation much easier.
CSS Selectors:
function DOMtoString() {
let lines = [];
let trs = document.querySelectorAll(
'div.contborda > table:nth-of-type(2) > tbody > tr:not(:first-child)'
);
trs.forEach(tr => {
let line = [];
let tds = tr.querySelectorAll('td');
tds.forEach(td => line.push(td.innerText.trim()));
lines.push(line.join('|'));
});
return lines;
}
console.log(DOMtoString());
<div class="dummy"></div>
<div class="contborda">
<table class="dummy"><tbody></tbody></table>
<table width="100%" border="0" cellpadding="2" cellspacing="0">
<tbody>
<tr>
<td class="TRNbarratabelac" width="3%">
<input type="checkbox" name="chkTodos" id="chkTodos" onclick="selTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNbarratabelac">Data do <br>pagamento</td>
<td class="TRNbarratabelac">Tipo</td>
<td class="TRNbarratabelac">Favorecido/beneficiário</td>
<td class="TRNbarratabelac">Valor (R$)</td>
<td class="TRNbarratabelac">Informações complementares</td>
<td class="TRNbarratabelac" colspan="2" width="20%">Opções</td>
</tr>
<tr>
<td class="TRNlicbe"><input type="checkbox" name="chkSel" id="chkSel" value="1" onclick="verSelTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNlicbe">21/02/2020 </td>
<td class="TRNliebe">Concessionárias</td>
<td class="TRNliebe"> </td>
<td class="TRNlidbe">57,43 </td>
<td class="TRNlicbe"> </td>
<td class="TRNlicbde" width="8%">Visualizar</td>
<td class="TRNlicbde" width="12%"><span>enviar por email</span> </td>
</tr>
</tbody>
</table>
</div>
If you have any other reasons you want to stick to using XPath, then you should use dot .// when you want to select nodes relative to nodeContext:
XPath:
function DOMtoString() {
let lines = [];
let path_tr = '//div[#class="contborda"]/table/tbody/tr[position()>1]';
let tr = document.evaluate(path_tr, document, null, XPathResult.ANY_TYPE, null);
let x = tr.iterateNext();
while (x) {
let line = [];
let path_td = './/td';
var td = document.evaluate(path_td, x, null, XPathResult.ANY_TYPE, null);
let y = td.iterateNext();
while (y) {
line.push(y.innerText.trim());
y = td.iterateNext();
}
lines.push(line.join('|'));
x = tr.iterateNext();
}
return lines;
}
console.log(DOMtoString());
<div class="dummy"></div>
<div class="contborda">
<table class="dummy"><tbody></tbody></table>
<table width="100%" border="0" cellpadding="2" cellspacing="0">
<tbody>
<tr>
<td class="TRNbarratabelac" width="3%">
<input type="checkbox" name="chkTodos" id="chkTodos" onclick="selTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNbarratabelac">Data do <br>pagamento</td>
<td class="TRNbarratabelac">Tipo</td>
<td class="TRNbarratabelac">Favorecido/beneficiário</td>
<td class="TRNbarratabelac">Valor (R$)</td>
<td class="TRNbarratabelac">Informações complementares</td>
<td class="TRNbarratabelac" colspan="2" width="20%">Opções</td>
</tr>
<tr>
<td class="TRNlicbe"><input type="checkbox" name="chkSel" id="chkSel" value="1" onclick="verSelTodos(this)" style="background:transparent;border:0px;"></td>
<td class="TRNlicbe">21/02/2020 </td>
<td class="TRNliebe">Concessionárias</td>
<td class="TRNliebe"> </td>
<td class="TRNlidbe">57,43 </td>
<td class="TRNlicbe"> </td>
<td class="TRNlicbde" width="8%">Visualizar</td>
<td class="TRNlicbde" width="12%"><span>enviar por email</span> </td>
</tr>
</tbody>
</table>
</div>

object HTMLInputElement JavaScript error

So basically, I'm doing a webpage to calculate my school marks but I can't get it to print the result at the input value... Instead, it prints [object HTMLInputElement]
Here's my JavaScript code:
<script type="text/javascript"> </script>
<script>
window.onload = function () {
var quran = document.getElementById('quran').value;
var islamic = document.getElementById('islamic').value;
var arabic = document.getElementById('arabic').value;
var english = document.getElementById('english').value;
var games = document.getElementById('games').value;
var pc = document.getElementById('pc').value;
var maths = document.getElementById('maths').value;
var chem = document.getElementById('chem').value;
var phys = document.getElementById('phys').value;
var bio = document.getElementById('bio').value;
var social = document.getElementById('social').value;
var result = Number(quran) + Number(islamic) + Number(arabic) + Number(english) + Number(games) + Number(pc) + Number(maths) + Number(chem) + Number(phys) + Number(bio) + Number(social);
}
function resultFunc() {
document.getElementById('result').value = result;
}
</script>
And here's the table with the inputs:
<table class="rwd-table">
<tr>
<th>المادة الدراسية</th>
<th>الدرجة العظمى</th>
<th>درجة الطالب</th>
</tr>
<tr>
<td data-th="Movie Title">القرآن الكريم</td>
<td data-th="Genre">20</td>
<td data-th="Year"> <input value="" id="quran" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">التربية الإسلامية</td>
<td data-th="Genre">40</td>
<td data-th="Year"> <input value="" id="islamic" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">اللغة العربية</td>
<td data-th="Genre">60</td>
<td data-th="Year"> <input value="" id="arabic" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">اللغة الإنجليزية</td>
<td data-th="Genre">60</td>
<td data-th="Year"> <input value="" id="english" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">البدنية</td>
<td data-th="Genre">20</td>
<td data-th="Year"> <input value="" id="games" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الحاسوب</td>
<td data-th="Genre">20</td>
<td data-th="Year"> <input value="" id="pc" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الرياضيات</td>
<td data-th="Genre">80</td>
<td data-th="Year"> <input value="" id="maths" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الكيمياء</td>
<td data-th="Genre">60</td>
<td data-th="Year"> <input value="" id="chem" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الفيزياء</td>
<td data-th="Genre">60</td>
<td data-th="Year"> <input value="" id="phys" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الأحياء</td>
<td data-th="Genre">40</td>
<td data-th="Year"> <input value="" id="bio" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<td data-th="Movie Title">الإجتماعيات</td>
<td data-th="Genre">40</td>
<td data-th="Year"> <input value="" id="social" style="width: 70px;" type="text"/> </td>
</tr>
<tr>
<th>المجموع</th>
<th>500</th>
<th> <input style="width: 70px; background-color: gray;" id="result" value="" readonly /> </th>
</tr>
<tr>
<th style="font-size: 20px;">النسبة</th>
<th></th>
<th> <input style="width: 70px; background-color: gray;" value="" readonly /> </th>
</tr>
<tr>
<th></th>
<th> <input onClick="resultFunc()" type="submit" id="submit" value="اضغط هنا لحساب النسبة المئوية" /> </th>
<th></th>
</tr>
</table>
Sorry for the Arabic words, just look at the code :)
I've even tried to print the result in a cell instead of an input tag, but it gave me a similar error instead of printing the result...
The issue appears to be due to the calculation occurring during the window.onload event. In order to calculate the values you should be able to move the code from the onload event to the resultFunc function and it will allow you to calculate the total when you click the button.
function resultFunc() {
var quran = document.getElementById('quran').value;
var islamic = document.getElementById('islamic').value;
var arabic = document.getElementById('arabic').value;
var english = document.getElementById('english').value;
var games = document.getElementById('games').value;
var pc = document.getElementById('pc').value;
var maths = document.getElementById('maths').value;
var chem = document.getElementById('chem').value;
var phys = document.getElementById('phys').value;
var bio = document.getElementById('bio').value;
var social = document.getElementById('social').value;
var result = Number(quran) + Number(islamic) + Number(arabic) + Number(english) + Number(games) + Number(pc) + Number(maths) + Number(chem) + Number(phys) + Number(bio) + Number(social);
document.getElementById('result').value = result;
}
Also note the reason why you get [object HTMLInputElement] is due to the scoping of the variable result. Since you declare var result in resultFunc the value is immediately lost. [object HTMLInputElement] is rendered, because window.result is also a shortcut to the element in the HTML document with the id of result.

How do I put randomly generated numbers into a table?

I need to put 6 randomly generated numbers in a an HTML table, I was wondering what would be the best solution, this is my JS code :
function GenerateNumber(){
var sResultat = "";
var iCompteur;
for(iCompteur=0;iCompteur<=6;iCompteur++)
{
sResultat = Math.round(Math.random()* 18) + 1;
}
}
Would calling them with the AddEventListener work? I need to make it appear everytime I load the page, and of course, the numbers need to be different if I reload the page.
Here is my HTML code : (I put numbers temporarily to test my code and to show where I want them to appear)
<div class="table">
<table>
<tr>
<th>FORce</th>
<th>DEXtérité</th>
<th>CONstitution</th>
<th>INTelligence</th>
<th>SAGesse</th>
<th>CHArisme</th>
</tr>
<tr>
<td class = "FOR">
5
</td>
<td class = "DEX">
4
</td>
<td class= "CON">
4
</td>
<td class ="INT">
4
</td>
<td class="SAG">
4
</td>
<td class="CHA">
3
</td>
</tr>
</table>
</div>
function generateNumber() {
var sResultat
var cells = ["FOR", "DEX", "CON", "INT", "SAG", "CHA"]
cells.forEach(function(cell) {
sResultat = Math.round(Math.random() * 18) + 1;
document.getElementsByClassName(cell)[0].innerText = sResultat
})
}
generateNumber()
<div class="table">
<table>
<tr>
<th>FORce</th>
<th>DEXtérité</th>
<th>CONstitution</th>
<th>INTelligence</th>
<th>SAGesse</th>
<th>CHArisme</th>
</tr>
<tr>
<td class="FOR">
</td>
<td class="DEX">
</td>
<td class="CON">
</td>
<td class="INT">
</td>
<td class="SAG">
</td>
<td class="CHA">
</td>
</tr>
</table>
</div>
function GenerateNumber(){
var tds = document.querySelectorAll('.table td');
return Array.prototype.forEach.call(tds, function(td){
td.innerHTML = Math.round(Math.random()*18) + 1;
});
}
window.onload = GenerateNumber;
<div class="table">
<table>
<tr>
<th>FORce</th>
<th>DEXtérité</th>
<th>CONstitution</th>
<th>INTelligence</th>
<th>SAGesse</th>
<th>CHArisme</th>
</tr>
<tr>
<td class = "FOR">
5
</td>
<td class = "DEX">
4
</td>
<td class= "CON">
4
</td>
<td class ="INT">
4
</td>
<td class="SAG">
4
</td>
<td class="CHA">
3
</td>
</tr>
</table>
</div>

How to update values of label on Focus out jquery event

I am trying to update my gridview by calculating a few things like TotalPrice and TotalPriceGST. The calculation part works fine. I want to update the fields of TotalPrice and TotalPriceGST when i leave the UnitPriceTxt textbox (On Focus Out). But when i do it with the following code it updates the first row and doesn't allow me to write the price in the later textboxes. Please Help!
<div>
<table cellspacing="0" cellpadding="4" id="ContentPlaceHolder1_gvQuotationItems" style="color:#333333;width:900px;border-collapse:collapse;float: left">
<tr style="color:White;background-color:#F07323;font-weight:bold;">
<th scope="col">Product Code</th>
<th scope="col">Description</th>
<th scope="col">Sap Pack</th>
<th scope="col">Quantity</th>
<th scope="col">UnitPrice</th>
<th scope="col">Total Price</th>
<th scope="col">Total Price with GST</th>
</tr>
<tr style="color:#333333;background-color:#F7F6F3;">
<td style="width:160px;">BCR123A-1EA</td>
<td style="width:250px;">23477, Reference ethanols (H, M, L) (for</td>
<td style="width:30px;">1</td>
<td style="width:60px;">12</td>
<td>
<input type="text" id="UnitPriceTxt" style="width:50px;" />
</td>
<td style="width:60px;"></td>
<td style="width:60px;">
<label id="TotalPriceGST"></label>
</td>
</tr>
<tr style="color:#284775;background-color:White;">
<td style="width:160px;">459-UP</td>
<td style="width:250px;">459 bubbler</td>
<td style="width:30px;">1</td>
<td style="width:60px;">123</td>
<td>
<input type="text" id="UnitPriceTxt" style="width:50px;" />
</td>
<td style="width:60px;"></td>
<td style="width:60px;">
<label id="TotalPriceGST"></label>
</td>
</tr>
<tr style="color:#333333;background-color:#F7F6F3;">
<td style="width:160px;">567-UP</td>
<td style="width:250px;">567 Unprepared Customer Bubbler Purchase</td>
<td style="width:30px;">1</td>
<td style="width:60px;">50</td>
<td>
<input type="text" id="UnitPriceTxt" style="width:50px;" />
</td>
<td style="width:60px;"></td>
<td style="width:60px;">
<label id="TotalPriceGST"></label>
</td>
</tr>
</table>
</div>
This is My Script:
$(function () {
$("#UnitPriceTxt").focusout(function () {
var TextBoxtxt = $('#<%=gvQuotationItems.ClientID %>').find('input:text[id$="UnitPriceTxt"]').val();
var TotalPriceLbl = $('#<%=gvQuotationItems.ClientID %>').find("#totalPrice");
var TotalPriceGSTLbl = $('#<%=gvQuotationItems.ClientID %>').find("#TotalPriceGST");
$("#<%=gvQuotationItems.ClientID %> tr").each(function () {
if (!this.rowIndex) return;
var Quantity = $(this).find("td:eq(3)").html();
var UnitPrce = $(this).find('input:text[id$="UnitPriceTxt"]').val();
var totalPrice = parseInt(Quantity) * parseInt(UnitPrce);
var GST = (parseInt(Quantity) * 17) / 100;
var TotalPriceGST;
TotalPriceGST = totalPrice + GST;
$(this).find("td:eq(5)").html('<label id="totalPrice" style="font-size:small" >' + totalPrice + ".Rs" + '</label>');
$(this).find("td:eq(6)").html('<label id="TotalPriceGST">' + TotalPriceGST + '</label>')
})
})
});
What you want is $('#UnitPriceTxt').blur(function(){...});
$.blur() is the "focus out" function you're looking for.

Categories

Resources