My goal is when a checkbox is clicked it's data-price should be added to the total variable and then this variable should be shown in the total price text box, however, it currently doesn't update the value when a checkbox is clicked.
Here is an interactive example of how it currently works/looks:
const form = document.getElementById('bookingForm');
const total = document.getElementsByName[0]('total');
document.getElementById("bookingForm").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let total = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
total += +box.dataset.price;
} //if
})
document.querySelector("[name=total]").innerHTML = total.toFixed(2);
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
const form = document.getElementById('bookingForm');
const total = document.getElementsByName('total');
var chksBoxes = document.querySelectorAll('.chkEvent');
chksBoxes.forEach(function(chk) {
chk.addEventListener("click", function(e) {
var total = 0;
chksBoxes.forEach(function(box) {
if (box.checked)
total += +box.dataset.price
});
document.querySelector("[name=total]").value = total.toFixed(2);
});
});
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1 </span>
<span class='eventPrice'>Price: 10.50</span>
<span class='chosen'><input type='checkbox' class="chkEvent" name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2 </span>
<span class='eventPrice'>Price: 5.00</span>
<span class='chosen'><input type='checkbox' class="chkEvent" name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
For Input elements you should use value instead of innerHTML
const form = document.getElementById('bookingForm');
const total = document.getElementsByName('total')[0];
document.getElementById("bookingForm").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let total = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
total += +box.dataset.price;
} //if
})
document.querySelector("[name=total]").value = total.toFixed(2);
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
PS: You have a typo at line# 2 where document.getElementsByName[0]('total'); should actually be document.getElementsByName('total')[0];
Related
I have a query selector for checkboxes which works fine and I replicated it for radio button, but I am running into the problem that they are both keeping separate totals. I tried to take the totalPrice variable out of both of them and place it outside so that it would be shared, but that created the problem of the price not being removed from unchecked checkboxes and radio buttons.
This is my current buggy code:
const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
document.getElementById("bookingForm").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let totalprice = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
totalprice += +box.dataset.price;
}
})
document.querySelector("[name=total]").value = totalprice.toFixed(2);
}
})
document.getElementById("bookingForm").addEventListener("click", function(e) {
if (e.target.name === "delivery") {
let totalprice = 0;
[...document.querySelectorAll('input[data-price][type=radio]')].forEach(function(box) {
if (box.checked) {
totalprice += +box.dataset.price;
}
})
document.querySelector("[name=total]").value = totalprice.toFixed(2);
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<input type="radio" name="delivery" value="ticket" data-price="10">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
Just have one event handler and one loop
If you only have data-price on the elements you need to loop, then you can change
[...document.querySelectorAll('input[data-price][type=checkbox], input[data-price][type=radio]')].forEach(function(box) {
to
[...document.querySelectorAll('input[data-price]')].forEach(function(box) {
I just wonder why you have a only a single radio - it cannot be un-selected. Why not another checkbox?
const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
form.addEventListener("click", function(e) {
if (e.target.name === "event[]" || e.target.name === "delivery") {
let totalprice = 0;
[...document.querySelectorAll('input[data-price][type=checkbox], input[data-price][type=radio]')].forEach(function(box) {
if (box.checked) {
totalprice += +box.dataset.price;
}
})
document.querySelector("[name=total]").value = totalprice.toFixed(2);
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<input type="radio" name="delivery" value="ticket" data-price="10">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
I want to check if any checkbox on the website has been checked when text has been entered in the name text box. I know that the EventListener works for name since this works without the document.getElementsByName("event[]").checked, but how do I make it work for the checkboxes?
document.getElementsByName("name")[0].addEventListener('change', (event) => {
if (event.target.value.length != 0 && document.getElementsByName("event[]").checked ) {
window.alert("checked");
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="Events">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<input type="radio" name="delivery" value="ticket" data-price="10">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
<p>Name<input type="text" name="name"></p>
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
I'd suggest:
document.getElementsByName("name")[0].addEventListener('change', (event) => {
// here we used event.target.value.trim.length in order to guard against
// white-space strings being considered valid (if that's not a problem
// then the trim() method can be removed), and also we used:
// document.querySelector() to find the first of any <input> element
// with a type equal to 'checkbox' which is also checked;
// document.querySelector() returns either the first such element or null:
if (event.target.value.trim().length > 0 &&
document.querySelector('input[type=checkbox]:checked') !== null) {
window.alert("checked");
}
});
document.getElementsByName("name")[0].addEventListener('change', (event) => {
if (event.target.value.trim().length > 0 &&
document.querySelector('input[type=checkbox]:checked') !== null) {
window.alert("checked");
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="Events">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<input type="radio" name="delivery" value="ticket" data-price="10">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
<p>Name<input type="text" name="name"></p>
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
It's worth adding that your first line could be potentially simplified a little using document.querySelector() rather than using indices:
document.querySelector("input[name=name]").addEventListener('change', (event) => {
if (event.target.value.trim().length > 0 &&
document.querySelector('input[type=checkbox]:checked') !== null) {
window.alert("checked");
}
});
document.querySelector('input[name=name]').addEventListener('change', (event) => {
if (event.target.value.trim().length > 0 &&
document.querySelector('input[type=checkbox]:checked') !== null) {
window.alert("checked");
}
});
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="Events">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<input type="radio" name="delivery" value="ticket" data-price="10">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
<p>Name<input type="text" name="name"></p>
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
References:
CSS:
Attribute-selectors ([attribute=attribute-value]).
:checked.
JavaScript:
document.querySelector().
String.prototype.trim()
//--Get all checkboxes, you can have another way of fetching checkboxes
var checkBoxes = document.getElementsByTagName("input");
//--For each checkbox, check if it is selected
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked == true) {
alert('checked');
}
}
Use document.querySelectorAll to get an array containing all the checkbox inputs in the document:
var checkboxes = document.querySelectorAll("input[type=checkbox]");
Then, to check if any of the checkboxes are checked:
var anyChecked = false;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
anyChecked = true;
break;
}
}
Alternatively, if you want an array containing only the checkboxes that are checked, you can do the following:
var checkedCheckboxes = checkboxes.filter(checkbox => checkbox.checked);
document.getElementsByName("name")[0].addEventListener('change', (event) => {
if(event.target.value.length !== 0) {
// Get all checkboxes
const checkboxes = document.getElementsByName("event[]");
for(i=0; i<checkboxes.length; i++) {
// Check if checkbox is checked or not
if(checkboxes[i].checked) {
window.alert("checked");
}
}
}
})
When I click on the checkbox at the top, it puts a '0' in the total box, so I know that it is connected correctly, however I think there is a problem in the logic in the loop. One of the elements in html looks like this.
const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
const checkboxes = document.querySelectorAll('input[data-price][type=checkbox]');
const cbamount = checkboxes.length;
document.getElementsByName('event[]')[0].onclick = function() {
totalPrice()
};
function totalPrice() {
let totalprice = 0;
for (let i = 0; i < cbamount; i++) {
const box = checkboxes[i];
if (box.checked) {
box.dataset.price = totalprice + box.dataset.price;
} //if
} //for
document.getElementsByName("total")[0].value = totalprice;
}
<span class="eventTitle">Carmen </span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">T</span>
<span class="venueName">Mill </span>
<span class="eventPrice">3</span>
<span class="chosen"><input type="checkbox" name="event[]" value="11" data-price="35.00"></span>
<section id="Cost">
<h3>Total</h3>
Total <input type="text" name="total" size="20" readonly="">
</section>
You have no total in the code you provided.
I would personally use ID when only having one element and if more, use relative addressing and/or delegation
const form = document.getElementById('booking');
const total = document.getElementById('total');
document.getElementById("booking").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let totalprice = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
totalprice += +box.dataset.price;
} //if
})
document.querySelector("[name=total]").value = totalprice.toFixed(2);
}
})
<form id="booking" method="get">
<section id="book">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Carmen </span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">T</span>
<span class="venueName">Mill </span>
<span class="eventPrice">3</span>
<span class="chosen"><input name="event[]" type="checkbox" value="11" data-price="35.00"></span>
</div>
<div class="item">
<span class="eventTitle">Ash</span>
<span class="eventStartDate">202</span>
<span class="eventEnd">2020-12-31</span>
<span class="catD">Exhib</span>
<span class="venueNa">The Biy</span>
<span class="eventPr">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="17" data-price="10.00"></span>
</div>
</section>
<section id="Cost">
<h3>Total</h3>
Total <input type="text" name="total" size="20" readonly="">
</section>
</form>
$("#button").click(function () {
var pp = []
var ing = []
for (var q = 1; q <= 6; q++) {
pp[q - 1] = $('input[name=P' + (q) + ']').is(":checked");
ing[q - 1] = $('div#ingp' + (q) + '').show();
}
for (var q = 1; q <= 6; q++) {
if (pp[q - 1] == true) {
ing[q - 1];
}
}
});
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingrediënten">
<div>
<h1>Kies extra ingredienten</h1>
</div>
<div id="ingp1"></div>
<div id="ingp2"></div>
<div id="ingp3"></div>
<div id="ingp4"></div>
<div id="ingp5"></div>
<div id="ingp6"></div>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>
So the problem I have is that when I look if one or more of P1 to P6 is check then it shows all 6 div with id ingp1 to ingp6.
I want it to show ingp1 when P1 is checked, and ingp3 when P3 is checked. You get it.
How do I do this (small thing I am only allowed to use javascript and jquery).
First of all add a common class names for the elements in the form and the div's in the container as I have given test1,test2 etc.
$('document').ready(function() {
var test
$("#Pi input[ type = 'checkbox']").click(function() {
var test = this.className
if ( this.checked == true )
{
$('#ingredienten .'+test).show()
console.log($('#ingrediënten .'+test))
}
else
{
$('#ingrediënten .'+test).hide()
}
})
})
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
</head>
<body>
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" class = "test1" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" class = "test2" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" class = "test3" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" class = "test4" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" class = "test5" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" class = "test6" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingredienten">
<div>
<h1>Kies extra ingredienten</h1></div>
<div id="ingp1" class = "test1">
</div>
<div id="ingp2" class = "test2">
</div>
<div id="ingp3" class = "test3">
</div>
<div id="ingp4" class = "test4">
</div>
<div id="ingp5" class = "test5">
</div>
<div id="ingp6" class = "test6">
</div>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>
</body>
<html>
Then take the class name of the clicked check-box and search the div with the class name of this check-box and show or hide the div depending on its checked property.
try this
for (var q = 1; q <= 6; q++)
{
if ( $( 'input[ name = "P' + q + '"]').is(":checked") )
{
$( 'div#ingp' + q ).show();
}
}
$("#button").click(function () {
$('input[name^=P]').each(function () {
var idx = this.name.replace('P', '');
$('div#ingp' + idx).toggle(this.checked);
});
});
In words
for each <input> whose name starts with 'P',
find the associated <div> with the proper ID
toggle its visibility based on whether the <input> is checked or not
#Ttech thanks for clarifying the SO to me. Here's my solution. I slightly changed the markup in the part concerning the ids of the extra ingredients section (the divs).
Please, check my working example and see if this is what you need.
$('#ingrediënten div').hide();
$('#knop').on('click', function() {
$('#ingrediënten div').hide();
var $checkedOptions = $('#Pi input[type=checkbox]').filter(':checked'),
$extraIngredients = $('#ingrediënten div');
$checkedOptions.each(function() {
var id = $(this).attr('name');
$extraIngredients.filter('[id=' + id + ']').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingrediënten">
<div>
<h1>Kies extra ingredienten</h1>
</div>
<div id="P1">
Extra ingredient 1
</div>
<div id="P2">
Extra ingredient 2
</div>
<div id="P3">
Extra ingredient 3
</div>
<div id="P4">
Extra ingredient 4
</div>
<div id="P5">
Extra ingredient 5
</div>
<div id="P6">
Extra ingredient 6
</div>
<br>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>
So I have a multi-input form with some fields that need to be added and some subtracted and to total to and display in a list that is displayed via a class. For some reason my math is not working to display the total. Ideally I would like to have the initial vehicle price start off populated in the first input box already and being displayed in the list that shows the total price. Can someone see what I am doing wrong please.
HTML:
<form class="form-inline" role="form">
<!--Adjust Vehicle Cost -->
<div class="form-group col-sm-6"> <span class="glyphicon glyphicon-usd"</span>
<label for="vehiclePrice">Vehicle Price</label>
<input type="number" class="form-control" id="vehiclePrice" placeholder="Vehicle Price" onkeypress="return isNumberKey(event)">
</div>
<div class="form-group col-sm-6"> <span class="glyphicon glyphicon-usd"</span>
<label for="estimatedTaxesAndFees">Estimated Taxes and Fees</label>
<input type="number" class="form-control" id="estimatedTaxesAndFees" placeholder="Estimated Taxes and Fees" onkeypress="return isNumberKey(event)">
</div>
</form>
<h6>DOWN PAYMENT & TRADE-IN</h6>
<hr>
<form class="form-inline" role="form">
<div class="form-group col-sm-6"> <span class="glyphicon glyphicon-usd"</span>
<label for="downPayment">Down Payment</label>
<input type="number" class="form-control" id="downPayment" placeholder="Down Payment" onkeypress="return isNumberKey(event)">
</div>
<div class="form-group col-sm-6"> <span class="glyphicon glyphicon-euro"</span>
<label for="manufacturerRebate">Manufacturer Rebate</label>
<input type="number" class="form-control" id="manufacturerRebate" placeholder="Manufacturer Rebate" onkeypress="return isNumberKey(event)">
</div>
<div class="form-group col-sm-6"> <span class="glyphicon glyphicon-usd"</span>
<label for="tradeInValue">Trade-In Value</label>
<input type="number" class="form-control" id="tradeInValue" placeholder="tradeInValue" onkeypress="return isNumberKey(event)">
</div>
<div class="form-group col-sm-6"> <span class="glyphicon glyphicon-usd"</span>
<label for="amtOwedOnTrade">Amt Owed on Trade</label>
<input type="number" class="form-control" id="amtOwedOnTrade" placeholder="Amt Owed on Trade" onkeypress="return isNumberKey(event)">
</div>
</form>
<h6>PROTECT YOUR PURCHASE</h6>
<hr>
<form class="form-inline" role="form">
<div class="form-group col-sm-6"> <span class="glyphicon glyphicon-euro"</span>
<label for="extendedWarranty">Extended Warranty</label>
<input type="email" class="form-control" id="extendedWarranty" placeholder="Extended Warranty" onkeypress="return isNumberKey(event)"></input>
</div>
<div class="form-group col-sm-6"> <span class="glyphicon glyphicon-euro"</span>
<label for="gapInsurance">Gap Insurance</label>
<input type="password" class="form-control" id="gapInsurance" placeholder="Gap Insurance" onkeypress="return isNumberKey(event)">
</div>
<div class="form-group col-sm-6"> <span class="glyphicon glyphicon-euro"</span>
<label for="serviceContract">Service Contract</label>
<input type="password" class="form-control" id="serviceContract" placeholder="Service Contract" onkeypress="return isNumberKey(event)">
</div>
</form>
<ul>
<li>$28,435</li><!--This always need to revert back if nothing is filled out-->
<li>Total Financed Amount<span class="glyphicon glyphicon-cloud"></span></li>
<li class="total"></li>
</ul>
<ul>
<li>5.30%</li>
<li>APR for 72 Months<span class="glyphicon glyphicon-cloud"></span></li>
<li></li>
</ul>
<ul class="fltrt">
<li>$461/mo</li>
<li>Estimated Payment<span class="glyphicon glyphicon-cloud"></span></li>
<li></li>
</ul>
JS:
$( document ).ready(function() {
console.log( "ready!" );
//vehicle price
$('#vehiclePrice').keyup(function() {
updateTotal();
});
//estimated taxes and fees
$('#estimatedTaxesAndFees').keyup(function() {
updateTotal();
});
//down payment
$('#downPayment').keyup(function() {
updateTotal();
});
//manufacturer rebate
$('#tradeInValue').keyup(function() {
updateTotal();
});
//trade in value
$('#manufacturerRebate').keyup(function() {
updateTotal();
});
//amt owed on trade
$('#amtOwedOnTrade').keyup(function() {
updateTotal();
});
//extended warranty
$('#extendedWarranty').keyup(function() {
updateTotal();
});
//gap insurance
$('#gapInsurance').keyup(function() {
updateTotal();
});
//service contract
$('#serviceContract').keyup(function() {
updateTotal();
});
var updateTotalAmtFinanced = function() {
var input1 = parseInt($('#vehiclePrice').val());
var input2 = parseInt($('#estimatedTaxesAndFees').val());
var input3 = parseInt($('#downPayment').val());
var input4 = parseInt($('#tradeInValue').val());
var input5 = parseInt($('#manufacturerRebate').val());
var input6 = parseInt($('#amtOwedOnTrade').val());
var input7 = parseInt($('#extendedWarranty').val());
var input8 = parseInt($('#gapInsurance').val());
var input9 = parseInt($('#serviceContract').val());
var max = 40000;
var basePrice = 28445;
var totalAmtFinanced = input1 + input2 - input3 + input4 + input5 + input6 + input7 + input8 + input9;
if (totalAmtFinanced > max) {
$('.total').text('The maximum is ' + max);
$('.total1').val(40000);
} else {
$('.total').text(totalAmtFinanced);
$('.total1').val(totalAmtFinanced);
}
};
});
The Fiddle
I suggest using a single listener on body, and filtering via selector...
$("body").on("keyup", "#gapInsurance,#foo,#bar", function () {
updateTotal();
});