I am very new at JavaScript so a step by step answer would be much appreciated. Right now my code is set up so when you click the submit button it displays the total but instead I would like the total to be updated automatically by just checking the checkboxes and to not have a submit button at all.
function calcTotal()
{
var itemTotal = 0;
var items = document.getElementsByTagName("input");
for (var i = 0; i < 5; i++) {
if (items[i].checked){
itemTotal += parseInt(items[i].value);
}
}
document.getElementById("total").innerHTML = "Your order total is $" + itemTotal +".00";
}
var submitButton = document.getElementById("sButton");
submitButton.addEventListener("click", calcTotal);
Actually you need to bind Checkbox's event change, instead of Form submit button click. That whenever you change checkbox value by checking or unchecking it, It call the function calcTotal() to update the value.
Here is updated Javascript code:
function calcTotal()
{
var itemTotal = 0;
var items = document.getElementsByTagName("input");
for (var i = 0; i < 5; i++) {
if (items[i].checked){
itemTotal += parseInt(items[i].value);
}
}
document.getElementById("total").innerHTML = "Your order total is $" + itemTotal +".00";
}
var checkBoxItems = document.getElementsByTagName("input");
checkBoxItems.addEventListener("change", calcTotal);
Hope it will help you.
Just add a change event to every checkbox. When you toggle the checked state, recalculate the total by grabbing the :checked checkboxes.
Array.from(document.querySelectorAll('input[type="checkbox"]')).forEach(chk => {
chk.addEventListener('change', recalculateTotal);
});
function recalculateTotal() {
let total = Array.from(document.querySelectorAll(':checked')).reduce((sum, chk) => {
return sum + parseInt(chk.value, 10);
}, 0);
document.getElementById('total').innerHTML = '$' + total.toFixed(2);
}
label { display: inline-block; margin-right: 1em; }
div { margin-top: 1em; }
<label>$1 <input type="checkbox" value="1" /></label>
<label>$10 <input type="checkbox" value="10" /></label>
<label>$100 <input type="checkbox" value="100" /></label>
<div>Your order total is: <span id="total">$0.00</span></div>
The key is listening to the input event on the input elements instead of the click event on the button element.
Additional notes, when possible:
Use single quotes in JS, double quotes in HTML
Use let or const instead of var
Don't reinvent .reduce when you need to reduce an array of values into a single value (e.g. compute a sum).
Use template strings (e.g. `y: ${y}`) instead of concatenating strings (e.g. "y: " + y).
let inputs = [...document.querySelectorAll("input")];
let calcTotal = () => {
let sum = inputs.reduce((sum, input) => sum + (input.checked ? parseInt(input.value) : 0), 0);
document.querySelector("#total").textContent = `Your order total is $${sum}.00`;
};
inputs.forEach(input => input.addEventListener('input', calcTotal));
<label><input type="checkbox" value=30>$30 hamburger</label>
<label><input type="checkbox" value=45>$45 french fries</label>
<label><input type="checkbox" value=1>$1 cola</label>
<label><input type="checkbox" value=60>$60 parking</label>
<label><input type="checkbox" value=20>$20 cookie</label>
<label><input type="checkbox" value=290>$290 large cookie</label>
<div id="total"></div>
Related
I have four sets of radio buttons, each containing four options as shown in the code below:
<div *ngFor="let index of [0,1,2,3]">
<label *ngFor="let vehicle of vehicles" class="radio">
<input type="radio"
id="radio1"
[value]="vehicle"
(change)="updateValues(vehicles, formArray.value, index)"
name="vehicle" formControlName="vehicle">
{{vehicle.name}} ({{vehicle.total_no}})
</label>
</div>
Each vehicle in the above option set has a name and total number attached to it. On selecting a vehicle, the total number value should update. The option should also be disabled if the total number is zero.
I have written a function that correctly updates the values, but it unfortunately registers changes in the other sets of radio buttons too.
updateValues(vehicles, form, index) {
let x;
let selectedVehicles = form.map(x => x.vehicle);
if (this._prevSelectedVehicles[index] === '') {
x = vehicles.indexOf(selectedVehicles[index]);
vehicles[x].total_no -= 1;
this._prevSelectedVehicles[index] = selectedVehicles[index];
this.updateTime(form, selectedVehicles);
} else if (
selectedVehicles[index].name !== this._prevSelectedVehicles[index].name
) {
x = vehicles.indexOf(this._prevSelectedVehicles[index]);
vehicles[x].total_no += 1;
x = vehicles.indexOf(selectedVehicles[index]);
vehicles[x].total_no -= 1;
this._prevSelectedVehicles[index] = selectedVehicles[index];
this.updateTime(form, selectedVehicles);
}
}
How can I make sure that the values selected in the previous divs are not updated? Also attaching a mockup if the question is unclear.
Use an unique ID for each vehicle-object and compare by this. E.g.
...
if(vehicles[x].id === this._prevSelectedVehicles[index].id){
x = vehicles.indexOf(this._prevSelectedVehicles[index]);
vehicles[x].total_no += 1;
x = vehicles.indexOf(selectedVehicles[index]);
vehicles[x].total_no -= 1;
this._prevSelectedVehicles[index] = selectedVehicles[index];
}
...
I'm beginer in js, please help me.
I have two functions. First function sum all checked input ticket and view sum price, secondary function check discount code and takes into account the new price.
The problem is when I add a discount code and then will choose a ticket. Then it does not calculate the value.
https://jsfiddle.net/wznvfkm3/
$('.participantEventTicket').on('change', function() {
var totalPrice = 0.00;
$('.participantEventTicket:checked').each(function() {
totalPrice += parseFloat($(this).data('price'), 10);
});
$('.participantEventTicketSum').html(totalPrice.toFixed(2));
$('.participantEventTicketDiscountValueTotal').html(totalPrice);
});
$('.participantEventTicketDiscount').on('change', function() {
var code = ($(this).val());
var valueTotal = document.getElementById('participantEventTicketSum').innerHTML;
var value = 0;
var liste = [];
liste[0] = ['ABB'], -5]; liste[1] = ['BBC'], -10];
for (var i = 0, len = liste.length; i < len; i++) {
if (liste[i][0] === code) {
var value = liste[i][1];
}
}
var valueTotalS = parseInt(valueTotal) + parseFloat(value);
$('#participantEventTicketDiscountValue').html(value.toFixed(2));
$('#participantEventTicketDiscountValueTotal').html(valueTotalS);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ticket 1
<input type="checkbox" name="participantEventTicket[]" value="5" class="participantEventTicket" />
<br/>ticket 2
<input type="checkbox" name="participantEventTicket[]" value="10" class="participantEventTicket" />
<br/>Sume tickets: <span class="participantEventTicketSum" id="participantEventTicketSum">0.00</span>
<br/>Discount coupon
<input type="text" id="participantEventTicketDiscount" class="participantEventTicketDiscount">
<br/>Discount value <span id="participantEventTicketDiscountValue" class="participantEventTicketDiscountValue">0.00</span>
<br/>Discount value sum <span id="participantEventTicketDiscountValueTotal" class="participantEventTicketDiscountValueTotal">0.00</span>
</form>
Slawotu,
Please check this fiddle
You had couple errors:
$('.participantEventTicket:checked').each(function () { totalPrice += parseFloat($(this).val(), 10);});
// you supposed to take $(this).val()
You didn't put calculation of total Price when you entered discount and changed you ticket:
$('.participantEventTicketDiscountValueTotal').html(totalPrice + value);
Forgot but brackets:
liste[0] = [['ABB'], -5];
liste[1] = [['BBC'], -10];
You compared 2 different objects using === instead use ==
if (liste[i][0] == code)
Declare val on top of the file, don't declare inside if statement.
var value = 0;
I would like to balance two input number fields using jquery based on the max value set for both. for example its like a balance, if one side goes down the other goes up and vice versa. another example if the max value is 20 then if i enter 5 in input field one then 15 would be left in input field two.
Need the help Thanks. Haven't started coding it as yet stuck trying to figure it out.
First you need to attach the input eventhandler on all of the relevant input fields. This event handler will compare the current input value of a input fields to the total/max value variable and find the remainder accordingly. The event handler then finds the other input fields and assigns them with the appropriate remainder values.
Note: This allows you to add as many inputs as you want and it will
balance them all out. Just remember to add the balance class on the
input field.
var total = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
this.value = value = 0;
} else if (value > total) {
this.value = value = total;
}/* else if (value < 0) {
this.value = value = 0;
}
* Remove this comment if value shouldn't be negative.
*/
var remainder = total - value;
var otherInputs = $('.balance');
otherInputs.splice($.inArray(this,otherInputs),1);
var remainderDiv = remainder/otherInputs.length;
$.each(otherInputs, function(input) {
otherInputs[input].value = remainderDiv;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
Update: The two inputs can be less than the max but never higher.
var max = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
value = 0;
}
var otherInputs = $('.balance');
var sum = 0;
$.each(otherInputs, function(input) {
sum += parseInt(otherInputs[input].value);
});
if (sum > max)
this.value = max - (sum - value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
here's a fiddle to get you started (and maybe finished):
https://jsfiddle.net/ahmadabdul3/xwyrrw53/1/
html:
<input type='number' id='first' class='balancable'/>
<input type='number' id='second' class='balancable'/>
js:
$(function() {
var max = 20;
var balanceOpposite = {
'first': 'second',
'second': 'first',
}
$('.balancable').on('input', function() {
var id = $(this).attr('id');
var thisVal = $(this).val();
$('#' + balanceOpposite[id]).val(20 - thisVal);
});
});
This is my HTML code:
<head>
</head>
<body>
LIMIT<input id='limit' name='' value='' class=''>
<button id='go' class=''>GO</button>
TOTAL<input id='total' name='' value='' class=''>
<script src='js/limitfor.js'></script>
</body>
And this is my JavaScript:
document.getElementById('go').onclick = function () {
var limit = document.getElementById('limit').value;
limit = parseFloat(limit);
total = 0;
for (i=0; i<=limit ;i++) {
total = total + i;
};
};
If I alert the total, I can see that the function works, but I need the total to be in the textbox rather than in a pop up alert.
You will need to set the value of the input element:
document.getElementById("total").value = total;
First select the particular element (i.e. total text field) in the form and set its value using assignment operator '='
document.getElementById("total").value=total;
Just assign the value in total text box after your for loop is completed
var limit = document.getElementById('limit').value;
limit = parseFloat(limit);
total = 0;
for (i=0; i<=limit ;i++) {
total = total + i;
};
document.getElementById("total").value = total;
};
use document.getElementById(put id of the text area where you want to output your answer or result).value = answer(whatever is your answer or result you want to reflect in textbox or textarea)
I need some help with javascript or jQuery.
I have three (3) input fields that I want to filter (sum of three fields).
the total value of 3 input fields is must 100. If the user fills more than 100, it will be automatically change the value that the total is 100.
you can see this example
<input type="text" name="text1" size="3"> text1<br />
<input type="text" name="text2" size="3"> text2<br />
<input type="text" name="text3" size="3"> text3<br />
<p>The maximum value of total 3 fields above is 100.</p>
<pre>example 1 :
text1 : 20;
text2 : 30;
text3 : 50; (will automatically filled with 50 because the total value must 100)</pre>
<pre>example 2 :
text1 : 37;
text2 : 60;
text3 : 3; (will automatically filled with 3 because the total value must 100)</pre>
Thanks for helping me,
I need it :)
$("input:lt(2)").on("change", function() {
var other = $("input:lt(2)").not(this).val();
if (other.length)
$("input:eq(2)").val(100 - this.value - other);
});
DEMO: http://jsfiddle.net/D5F3p/3/
This is the simplest thing I can think of!
$(document).ready(function(){
$('input[name="text2"]').blur(function(){
$('input[name="text3"]').val(100 - $('input[name="text1"]').val() - $('input[name="text2"]').val());
});
});
IMO, you can do these:
Give only two characters for both the inputs. Don't allow more than that!
You also need to check if the sum of the two inputs should not exceed 101!
Keep the input 2 readonly, until something has been entered in input 1.
Keep the input 3 always readonly.
Fiddle: http://jsfiddle.net/praveenscience/D5F3p/5/
<head>
<script type="text/javascript">
function check() {
var sum = 0;
var inputs = $(".test");
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value == parseInt(inputs[i].value)) {
sum += parseInt(inputs[i].value);
if (sum > 100) {
sum -= parseInt(inputs[i].value);
inputs[i].value = 100-sum;
}
}
}
}
</script>
</head>
<body>
<input type="text" onkeyup="check()" class="test" size="3">
<input type="text" onkeyup="check()" class="test" size="3">
<input type="text" onkeyup="check()" class="test" size="3">
$(function(){
$('input[name="text1"]').keyup(function(){
var text1Value = $('input[name="text1"]').val();
if(text1Value >=100)
{
$('input[name="text1"]').val(100);
$('input[name="text2"]').val('');
$('input[name="text3"]').val('');
$('input[name="text2"]').attr('disabled','disabled');
$('input[name="text3"]').attr('disabled','disabled');
}
else
{
$('input[name="text2"]').removeAttr('disabled');
$('input[name="text3"]').removeAttr('disabled');
}
});
$('input[name="text2"]').keyup(function(){
var text1Value = parseInt($('input[name="text1"]').val());
var text2Value = parseInt($('input[name="text2"]').val());
if(isNaN(text1Value))
{
text1Value =0;
}
if(isNaN(text2Value))
{
text2Value =0;
}
var total = text1Value + text2Value;
if(total >=100)
{
$('input[name="text2"]').val(100-text1Value);
$('input[name="text3"]').val('');
$('input[name="text3"]').attr('disabled','disabled');
}
else
{
$('input[name="text3"]').removeAttr('disabled');
$('input[name="text3"]').val(100-total);
}
});
});
I am checking if sum of all text boxes if exceeding 100, then making correction in the last entered textbox with disabling the next textbox.