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;
Related
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>
I tried some codes, but none worked. I have an amount due that should change when the quantity number from the drop-down list changes. So if someone changes the number of order it should multiply by the base number of desktop and the result should be the total amount. Here is part of my code which I think is relative to calculation part.
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
<div class=" products">
<div class="form-group">
<label for="chkYes1">
<input type="checkbox" id="desktops" name="" value="desktops" />
desktop $185.00
</label>
</div>
<select id="selectbasic" name="" class="">
<option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
</select>
</div>
<div class="form-group border border-dark rounded py-3 px-5">
<h3>Amount Due: <p id="amountDue">0</p>
</h3>
</div>
I have found a solution:
First, remove this code snippet since it's currently throwing an error:
computerType.onchange = function () {
document.getElementById("desktops").checked = false;
};
Second, declare these two variables to store the <select> tag element & the future selected value like so:
var selectOptions = document.getElementById("ddlViewBy");
var selectedValue;
Third, add this method to get the selected value & multiply the total like so:
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
For your reference, here is the full code sample:
var amountDue = document.getElementById("amountDue");
var desktopAddOns = document.querySelectorAll(".products");
var selectOptions = document.getElementById("selectbasic");
var selectedValue;
var total = 0;
var price = 0;
//Removes the add on options from view
document.getElementById("desktops").onchange = function () {
if (document.getElementById("desktops").checked) {
price = 185;
} else if (document.getElementById("desktops").checked == false) {
price = 185;
removeAddOns(price);
}
addAddOns(price);
};
//amountDue.innerHTML += total;
function addAddOns(price) {
total += price;
amountDue.innerHTML = total;
}
function removeAddOns(price) {
total -= price * 2;
amountDue.innerHTML = total;
}
selectOptions.addEventListener('change', () => {
selectedValue = selectOptions.options[ selectOptions.selectedIndex].value;
amountDue.innerHTML = Math.round(total * selectedValue);
})
You can also check this working code sample.
If you have questions about the code, let me know.
I have pushed an input value to an empty array and converted it into a number. I am trying to add up the array and show the sum. But the whole array is shown and no addition has been done. I've included some of the code here but I'll also include the JS fiddle in case I forgot something important. I may be overthinking it as I have been looking at it for sometime.
JS Fiddle: https://jsfiddle.net/nzart/emruz0sb/4/
// HTML
<h1>Sugar Counter:</h1><p id="total">--</p>
<div class="box bot1">
<div class="twogrid mid">
<label for="amount">Amount of Sugar</label>
<input type="text" name="amount" id="amount">
</div>
</div>
//JS
var added = [];
//Get Data
var userInput = function(){
return parseFloat(document.getElementById('amount').value);
}
// Store Data
var newSugar = function(){
return added.push(userInput());
}
//Add total
function total() {
var sum = 0;
for (var i = 0; i < added.length; i++) {
sum += added[i];
}
document.getElementById('total').textContent = added;
}
This line is incorrect inside of function total():
document.getElementById('total').textContent = added;
Change to this:
document.getElementById('total').textContent = sum;
Here is an updated fiddle: https://jsfiddle.net/bqt1mws7/
You are displaying the array variable not the sum variable. Assign the sum variable to #total, not added variable.
document.getElementById('total').textContent = sum;
You need a button to perform the summation to update the total.
The Array.prototype.reduce function is a easy way to total values inside of a list.
values.reduce((runningTotal, currentValue) => runningTotal + currentValue, initialValue)
var valueList = [];
document.getElementById('btn-add').addEventListener('click', onAddClick);
function onAddClick(e) {
var value = getCurrentValue();
if (isNaN(value)) {
alert('Value is not a number!');
return;
}
valueList.push(value);
document.getElementById('total').textContent = getTotal();
}
function getCurrentValue() {
return parseFloat(document.getElementById('amount').value.trim());
}
function getTotal() {
return valueList.reduce((a, b) => a + b, 0); // Sum the values in the list
}
<h1>Sugar Counter:</h1>
<label>Total:</label>
<span id="total">--</span>
<div class="box bot1">
<div class="twogrid mid">
<label for="amount">Amount of Sugar</label>
<input type="text" name="amount" id="amount">
<input type="button" value="Add" id="btn-add" />
</div>
</div>
There is no problem in the addition process. If the array is valid, the total() function will work well. But at the last statement of total() function, you put added variable as output. But it should be the value of sum variable.
function total() {
var sum = 0;
for (var i = 0; i < added.length; i++) {
sum += added[i];
}
document.getElementById('total').textContent = sum;
}
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);
});
});
For some reason only the score0 wants to increment. Although the two for-loops seem identical (really sorry if I'm wrong). So the totScore just gets the value from the score0 variable. But ofcourse I want totScore to get value form both variables so to get the total score of the quiz.
Also, why does it add 4 to the score0 variable when I wrote score0 += 1;, that doesn't make any sence to me.
If you change my code alot please don't use any JQuery.
Thanks!
<!DOCTYPE html>
<html>
<body>
<form id='quizForm'>
<ul>
<li>
<h3>How many letters are there in 'FB'?</h3>
<input type="radio" name="question0" value="A" />2<br>
<input type="radio" name="question0" value="B" />1<br>
<input type="radio" name="question0" value="C" />3<br>
<input type="radio" name="question0" value="D" />4<br>
</li>
</ul>
<ul>
<li>
<h3>How many letters are there in 'IBM'?</h3>
<input type="radio" name="question1" value="A" />2<br>
<input type="radio" name="question1" value="B" />1<br>
<input type="radio" name="question1" value="C" />3<br>
<input type="radio" name="question1" value="D" />4<br>
</li>
</ul>
</form>
<button onclick="showScore()">Show results
</button>
<script>
//Score and answer variables
var score1 = 0;
var score0 = 0;
var totScore = 0;
var answers = ["A","C"]
//function to calculate the score.
function getScore() {
// some arrays and stuff
userInput1 = new Array(10);
userInput0 = new Array(10);
var question0s = document.getElementsByName("question0");
//for loop to see which radio was checked
for (var i = 0; i < question0s.length; i++) {
if (question0s[i].checked) {
userInput0[0] = question0s[i].value;
}
if (userInput0[0] == answers[0]) {
// Only god knows why the hell I have to divide 4
score0 += 1 / 4;
}
else if (userInput0[0] != answers [0]){
//so that user can't just switch back and fourth from inputs to get higher score.
score0 -= 1 ;
}
}
//if user has changed her answer multiple times she will get an answer with a negative value. I don't want that, so if score is less than 0 it turns to 0.
if (score0 < 0){
score0 = score0 * 0;
}
var question1s = document.getElementsByName("question1");
//for loop to see which radio was checked
for (var y = 0; y < question1s.length; y++) {
if (question1s[y].checked) {
userInput1[0] = question1[y].value;
}
if (userInput1[0] == answers[0]) {
score1 += 1;
}
else if (userInput1[0] != answers [0]){
//so that user can't just switch back and fourth from inputs to get higher score.
score1 -= 1 ;
}
}
if (score1 < 0){
//if user has changed her answer multiple times she will get an answer with a negative value. I don't want that, so if score is less than 0 it turns to 0.
score1 = score1 * 0;
}
//getting score from all different questions
totScore += score1 + score0;
}
//checking for changes in the form
var quizForm = document.getElementById('quizForm');
quizForm.addEventListener("change", function(){
getScore();
});
// onclick function
function showScore (){
alert (totScore);
}
</script>
</body>
</html>
As to why you are not getting proper processing, you have an invalid variable question1 here:
userInput1[0] = question1[y].value;
Now let's fix this and do better.
First off, you have a number of global variables so let's get that under a simple namespace and call it quiz.
Get the click handler out of the markup and create a listener for that.
Now as for your logic, you are looping through the radio buttons. Now the way radio buttons work is that only one can be selected SO, let's use that to our advantage an not do the loop at all.
With the radio buttons, if one is NOT selected yet, then it will be NULL using our new selection technique so we can use that to tell if both the questions have been answered and then if that IS true, we can put scores in. Otherwise, they get no score (score is 0) until all the questions ARE answered (not NULL).
//Score and answer variables=
var quiz = {
score0: 0,
score1: 0,
totalScore: 0,
answers: ["A", "C"],
maxScore: 2,
tries: 0
};
//function to calculate the score.
function getScore() {
var answer0 = document.querySelector('input[name="question0"]:checked');
quiz.score0 = answer0 != null && quiz.answers[0] == answer0.value ? 1 : 0;
var answer1 = document.querySelector('input[name="question1"]:checked');
quiz.score1 = answer1 != null && quiz.answers[1] == answer1.value ? 1 : 0;
// if either is null, not all answered
if (answer0 != null && answer1 != null) {
// if previous tries, subtract how many
if (quiz.tries) {
quiz.totalScore = quiz.totalScore ? quiz.totalScore - quiz.tries : 0;
quiz.totalScore = quiz.totalScore < 0 ? 0 : quiz.totalScore ;//0 if negative
} else {
quiz.totalScore = quiz.score1 + quiz.score0;
}
quiz.tries++;
}
}
// onclick function
function showScore() {
alert(quiz.totalScore + " in tries: " + quiz.tries);
}
// add listeners
//checking for changes in the form
var quizForm = document.getElementById('quizForm');
quizForm.addEventListener("change", function() {
getScore();
});
var resultButton = document.getElementById('results');
resultButton.addEventListener("click", function() {
showScore();
});
Try the above out here: https://jsfiddle.net/MarkSchultheiss/qx4hLjLq/2/
You could also do more with this by putting that in the quiz something like this:
//Score and answer variables=
var quiz = {
totalScore: 0,
tries: 0,
maxScore: 2,
answered: 0,
questions: [{
question: {},
name: "question0",
score: 0,
answer: "A"
}, {
question: {},
name: "question1",
score: 0,
answer: "C"
}],
checkQuestion: function(q) {
q.score = q.question != null && q.answer == q.question.value ? 1 : 0;
},
//function to calculate the score.
getScore: function() {
this.answered = 0;
for (var i = 0; i < this.questions.length; i++) {
var sel = 'input[name="' + this.questions[i].name + '"]:checked';
this.questions[i].question = document.querySelector(sel);
this.checkQuestion(this.questions[i]);
this.answered = this.questions[i].question ? this.answered + 1 : this.answered;
}
console.dir(this);
// if either is null, not all answered
if (this.answered == this.questions.length) {
for (var i = 0; i < this.questions.length; i++) {
this.totalScore = this.totalScore + this.questions[i].score;
}
if (this.tries) {
this.totalScore = this.tries && this.totalScore ? this.totalScore - this.tries : 0;
this.totalScore = this.totalScore < 0 ? 0 : this.totalScore; //0 if negative
}
this.tries++;
}
},
// onclick function
showScore: function() {
var t = "";
if (this.answered != this.questions.length) {
t = "Not all questions ansered!"
} else {
t = this.totalScore + " in tries: " + this.tries;
}
alert(t);
}
};
// add listeners
//checking for changes in the form
var quizForm = document.getElementById('quizForm');
quizForm.addEventListener("change", function() {
quiz.getScore();
});
var resultButton = document.getElementById('results');
resultButton.addEventListener("click", function() {
quiz.showScore();
});
Second example in action: https://jsfiddle.net/MarkSchultheiss/qx4hLjLq/4/
Well if you want to simply get the result from the test, use this code:
<!DOCTYPE html>
<html>
<body>
<ul>
<li>
<h3>How many letters are there in 'FB'?</h3>
<input type="radio" name="question0"/>1<br>
<input type="radio" name="question0"/>2<br>
<input type="radio" name="question0"/>3<br>
<input type="radio" name="question0"/>4<br>
</li>
</ul>
<ul>
<li>
<h3>How many letters are there in 'IBM'?</h3>
<input type="radio" name="question1"/>1<br>
<input type="radio" name="question1"/>2<br>
<input type="radio" name="question1"/>3<br>
<input type="radio" name="question1"/>4<br>
</li>
</ul>
<button onclick="calculate()">Submit</button>
<script>
function calculate(){
var answers = [1, 2];
var score = 0;
var question0s = document.getElementsByName("question0");
var question1s = document.getElementsByName("question1");
if (question0s[answers[0]].checked == true) {
score++;
}
if (question1s[answers[1]].checked == true) {
score++;
}
alert ("You got " + score + " out of " + answers.length + ".");
}
</script>
</body>
</html>
It looks like you're calling the script every time an answer changes, and this is very inefficient. I'm only calling when all the answers have been made and the user presses submit.
And the reason why that is adding 4 times is because if you set your first answer to A, it writes it to userinput0 and doesn't get changed anymore since the answer was the only one checked, and it repeats the amount of choices there are, in which there were 4. Thus you are repeating that assignment statement 4 times so you are adding 4.