How to update values of label on Focus out jquery event - javascript

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.

Related

How do I sum all columns in a table with the same classname in JavaScript?

I am trying to sum a price in a table, all the prices in the <td> have the same class name and I'd like to sum them up on a button click. I would eventually like to calculate the quantity into the total as well. This is what I have so far:
function sumAmounts() {
var sum = 0;
var listPriceTotal = $('.txtListPrice').each(function() {
sum += parseFloat($(this).html); // Or this.innerHTML, this.innerText
});
document.getElementById("txtTotal").value = listPriceTotal;
}
document.getElementById("addTotals").addEventListener("click", () => {
sumAmounts();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<th><label>SKU</label></th>
<th><label>Retail Price</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tr>
<td class="txtSKU">1234</td>
<td class="txtRetailPrice">12.50</td>
<td class="txtListPrice">11.75</td>
<td class="txtProductName">product 1</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tr>
<td class="txtSKU">12222</td>
<td class="txtRetailPrice">14.50</td>
<td class="txtListPrice">9.75</td>
<td class="txtProductName">product 2</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tfoot>
<th><label id="lblTotal">Total:</label><input type="text" name="txtTotal" id="txtTotal">
<input type="button" value="Add" id="addTotals">
</th>
</tfoot>
</table>
There's two issues in your code. Firstly you're trying to set a jQuery object as the value of the input, which is why you see [Object object] in the field. You need to set the value to sum.
The second issue is that you're supplying the html method reference to parseFloat(), not the actual html() value. With both of those addressed, the code works:
function sumAmounts() {
var sum = 0;
$('.txtListPrice').each(function() {
sum += parseFloat($(this).html());
});
document.getElementById("txtTotal").value = sum;
}
document.getElementById("addTotals").addEventListener("click", () => {
sumAmounts();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
<tr>
<th><label>SKU</label></th>
<th><label>Retail Price</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tr>
<td class="txtSKU">1234</td>
<td class="txtRetailPrice">12.50</td>
<td class="txtListPrice">11.75</td>
<td class="txtProductName">product 1</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tr>
<td class="txtSKU">12222</td>
<td class="txtRetailPrice">14.50</td>
<td class="txtListPrice">9.75</td>
<td class="txtProductName">product 2</td>
<td class="txtQuantity"><input type="text"> </td>
</tr>
<tfoot>
<th>
<label id="lblTotal">Total:</label>
<input type="text" name="txtTotal" id="txtTotal">
<input type="button" value="Add" id="addTotals">
</th>
</tfoot>
</table>

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...

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.

Total value with jquery on table

I tried to calculate the total on the table using jquery, but when run totals do not appear. so I want to show the total live when I enter the input value, total auto-summing, what's wrong?
HTML
<table class="table table-condensed">
<thead>
<tr>
<td class="text-left"><strong>Product</strong></td>
<td class="text-center"><strong>Value</strong></td>
</tr>
</thead>
<tbody>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_a" name="producta" value="12.000"></td>
</tr>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_b" name="producta" value="19.000"></td>
</tr>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_c" name="producta" value="15.000"></td>
</tr>
<tr>
<td class="thick-line"><strong>Total</strong></td>
<td class="thick-line"><input type="text" id="total" name="total" /></td>
</tr>
</tbody>
</table>
JS
jQuery(document).ready(function(){
var total = ($('#product_a').val() + $('#product_b').val() + $('#product_c').val()) ;
$('#total').val(total);
});
You're doing it wrong. val() returns a string on an input[type=text] and currently you're just concatenating string values.
I want to show the total live when I enter the input value
Then, you need to add a listener when the inputs are being changed as you type. This could be done with keyup event.
E.g.
$(function() {
var $aProduct = $('#product_a'),
$bProduct = $('#product_b'),
$cProduct = $('#product_c'),
$total = $('#total'),
runTotal = function() {
var a = parseInt($aProduct.val()),
b = parseInt($bProduct.val()),
c = parseInt($cProduct.val());
$total.val(a + b + c);
};
$('.inputVal').on('keyup', runTotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed">
<thead>
<tr>
<td class="text-left"><strong>Product</strong>
</td>
<td class="text-center"><strong>Value</strong>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_a" name="producta" class="inputVal" value="12.000">
</td>
</tr>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_b" name="productb" class="inputVal" value="19.000">
</td>
</tr>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_c" name="productc" class="inputVal" value="15.000">
</td>
</tr>
<tr>
<td class="thick-line"><strong>Total</strong>
</td>
<td class="thick-line">
<input type="text" id="total" name="total" />
</td>
</tr>
</tbody>
</table>
Hi try following code....
jQuery(document).ready(function(){
$("input").on("change",updateTotal); // this will total on change input.
updateTotal(); //this will total on start..
});
function updateTotal()
{
var total = ($('#product_a').val()*1 + $('#product_b').val()*1 + $('#product_c').val()*1) ;
//By multiplying 1 to any string format number it will convert to number datatype.
//var total = (Number($('#product_a').val()) + Number($('#product_b').val()) + Number($('#product_c').val()));
//You can also uncomment above line to get your desire output.
$('#total').val(total);
}

checkbox logic not working correctly

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.

Categories

Resources