I am have a cart with items where each item, when clicked, will update the item count and price.
return {
itemCount: 0,
price: 0,
itemAdd: function () {
this.itemCount += 1;
if (this.itemCount <= 5) {
this.price = 500 + (110 * this.itemCount)
} else if (this.itemCount > 5, this.itemCount <= 10) {
this.price = 1000 + (105 * this.itemCount)
} else if (this.itemCount > 10) {
this.price = 1500 + (90 * this.itemCount)
}
document.getElementById("itemPrice").innerText = this.price;
document.getElementById("itemCount").innerText = this.itemCount;
},
}
}
When I click on one item twice, the price and itemCount is updated accordingly. However, when I click on a new item, the itemCount and price "reset" and start from zero. When I go back and click on the first item again, it continues counting from 2. What am I not getting right here?
Now update to this..
let price = 0;
let itemCount = 0;
const getData = () => {
return {
items: [],
itemAdd: function() {
itemCount += 1;
if (itemCount <= 5) {
price = 500 + 110 * itemCount;
} else if ((itemCount > 5, itemCount <= 10)) {
price = 1000 + 105 * itemCount;
} else if (itemCount > 10) {
price = 1500 + 90 * itemCount;
}
document.getElementById("itemPrice").innerHTML = price;
document.getElementById("itemCount").innerHTML = itemCount;
}
};
};
Related
i have this function and can change the value between 1 and 2.
How to change this function to increment up to 120? (120 is limit)
const decrementAmount = () => {
let newAmount = Amount - 1;
if (newAmount < 1) {
newAmount = 1;
}
setAmount(newAmount);
};
const incrementAmount = () => {
let newAmount = Amount + 1;
if (newAmount > 2) {
newAmount = 2;
}
setAmount(newAmount);
};
I got it!
i changed my limit: "newAmount = 20;"
const decrementAmount = () => {
let newAmount = Amount - 1;
if (newAmount < 1) {
newAmount = 1;
}
setAmount(newAmount);
};
const incrementAmount = () => {
let newAmount = Amount + 1;
if (newAmount > 20) {
newAmount = 20;
}
setAmount(newAmount);
};
I'm trying to set the property of an object with a function but instead, I get a value of 100 and the slide bar stuck in the middle. What am I doing wrong? Here is my code:
term: {
min: 1,
max: function(){
var period = document.getElementById("duration").value;
if (this.period == "days"){
var value = 31;
} else if(this.period == "months"){
value = 12;
} else {
value = 365;
};
return value;
},
step: 1,
_value: 10,
get value() {
return parseFloat(this._value);
},
set value(val) {
this._value = val;
},
reset: function() {
this._value = 12;
}
},
And this is the result on th UI:
EDIT:
This is how I use min and max:
document.querySelectorAll('.controller-row')
.forEach(function(group) {
var min = inputValues[group.id].min;
var max = inputValues[group.id].max;
var value = inputValues[group.id].value;
var step = inputValues[group.id].step;
var boundary = max ? 100 * (value - min) / (max - min) : 0;
var range = group.querySelector('input[type=range]');
range.setAttribute('style',
'background-image: linear-gradient(90deg, #4098FF 0%, #4098FF ' + boundary + '%, white ' + boundary + '%);'
);
range.min = min;
range.max = max;
range.value = value;
range.step = step;
var textInput = group.querySelector('input[type=number]');
textInput.min = min;
textInput.max = max;
textInput.value = value;
textInput.step = step;
});
I have created a simple script using recursion, to change the position of images.
It loop throught them and adjust their position , the script is relative easy code :
var img = document.getElementsByClassName("container")[0];
var X = 0;
var Y = 0;
var check;
function all() {
var decko = img.children;
for (var i = 0; i < decko.length; i++) {
if (i !== 0 && i % 3 === 0) {
X = 0;
Y++;
}
decko[i].style.transform = "translate3d(" + X * 100 + "px," + Y * 100 + "px,0)";
X++;
}
X = 0;
Y = 0;
check = false;
}
all()
window.onclick = function() {
pushIt(img.length, img.children, 0, 0)
}
function pushIt(max, target, index, count) {
if (count == max) {
return;
}
var tmp = target[index];
var matrix =window.getComputedStyle(tmp).getPropertyValue("transform");
var translate_left=matrix.split(",")[4];
var translate_top=matrix.split(",")[5].split(")")[0]-100;
tmp.style.transform = "translate3d(" + translate_left + "px," + translate_top + "px,0)";
setTimeout(function(){
pushIt(max, target, index + 1, count + 1);
},150)
}
Here you can see how it works. The problem is when there are a lot of images.
When i click which invokes the function , it loops throught all images ( 30 + in my case ). If i click two times in a sec , it will loop throught the all images , and THEN it will execute the function 2 nd time which is in my case unwanted behavior ( looks laggy ). Is there any way to prevent this behavior? I have chosen recursion , bcs it seems like easiest choice for this.
You had a couple if issues with your JavaScript that were throwing some errors, namely max was undefined in your function. I got this working HERE
var img = document.getElementsByClassName("container")[0];
var decko = img.children;
var X = 0;
var Y = 0;
var check;
var running = false;
function all() {
for (var i = 0; i < decko.length; i++) {
if (i !== 0 && i % 3 === 0) {
X = 0;
Y++;
}
decko[i].style.transform = "translate3d(" + X * 100 + "px," + Y * 100 + "px,0)";
X++;
}
X = 0;
Y = 0;
check = false;
}
all()
window.onclick = function () {
if (!running) {
running = true;
pushIt(decko.length, img.children, 0, 0);
}
}
var pushIt = function (max, target, index, count) {
if (count == max) {
running = false;
return;
}
var tmp = target[index];
var matrix = window.getComputedStyle(tmp).getPropertyValue("transform");
var translate_left = matrix.split(",")[4];
var translate_top = matrix.split(",")[5].split(")")[0] - 100;
tmp.style.transform = "translate3d(" + translate_left + "px," + translate_top + "px,0)";
setTimeout(function () {
console.log(running);
pushIt(max, target, index + 1, count + 1);
}, 150)
}
Iam working on an application, in the Grand Total field, its showing the sum of all the margin fields totals. But when the page loads its showing NaN in the total field. How can i show the existing total to show up in the Grand Total field?
This is my script.
demo
js
function getIndexedElement(item, index) {
if (item.length) {
if (index < item.length) {
return item[index];
} else {
return false;
}
} else {
if (index === 0) {
return item;
}
}
return false;
}
function isNum(value) {
return 123;
}
function calcTotals() {
var grandTotal = 0;
var margin_total = 0;
var total_inr1 = 0;
var i = 0;
while (getIndexedElement(document.forms['cart'].elements['add_percentage[]'], i)) {
add_percentageObj = getIndexedElement(document.forms['cart'].elements['add_percentage[]'], i);
addon_valueObj = getIndexedElement(document.forms['cart'].elements['addon_value[]'], i);
total_inr_valueObj = getIndexedElement(document.forms['cart'].elements['total_inr[]'], i);
totalObj = getIndexedElement(document.forms['cart'].elements['add_value[]'], i);
priceunitObj = getIndexedElement(document.forms['cart'].elements['price_unit[]'], i);
qtyObj = getIndexedElement(document.forms['cart'].elements['qty[]'], i);
marginObj = getIndexedElement(document.forms['cart'].elements['margin_for[]'], i);
if (isNaN(add_percentageObj.value)) {
add_percentageObj = '';
}
if (isNaN(addon_valueObj.value)) {
addon_valueObj = '';
}
if (add_percentageObj.value != 0) {
totalObj.value = (((total_inr_valueObj.value * 1) * add_percentageObj.value / 100) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total * 1) + marginObj.value * 1);
//total_inr1 = total_inr1 + parseFloat(total_inr_valueObj.value);
//c.value=Math.round((b.value/100) *a.value ).toFixed(2);
} else if (addon_valueObj.value != 0) {
totalObj.value = ((addon_valueObj.value * 1) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total * 1) + marginObj.value * 1);
//total_inr1 = total_inr1 + parseFloat(total_inr_valueObj.value);
} else {
totalObj.value = ((addon_valueObj.value * 1) + total_inr_valueObj.value * 1).toFixed(3);
grandTotal = grandTotal + parseFloat(totalObj.value);
marginObj.value = ((totalObj.value * 1) - (total_inr_valueObj.value * 1)).toFixed(3);
margin_total = ((margin_total * 1) + marginObj.value * 1);
//total_inr1 = total_inr1 + parseFloat(total_inr_valueObj.value);
}
i++;
}
//document.getElementById('grand_total').value = grandTotal.toFixed(3);
//document.getElementById('margin_total').value = margin_total.toFixed(3);
//document.getElementById('total_inr1').value = total_inr1.toFixed(3);
//document.getElementById('margin_for').value = margin_for;
marginTotal();
return;
}
function marginTotal() {
var x = $('[name="gt[]"]:checked').length;
if (x != 0) return;
var sum = 0;
$('input[name="margin_for[]"]').each(function () {
sum += +this.value;
});
$("#total12").val(sum);
}
$(function () {
$("input[type='checkbox'").on("change", function () {
recalcTotal();
}).change();
function recalcTotal() {
var total12 = 0;
var checkedinput = $("input:checked");
var targetcheckboxes = checkedinput.length ? checkedinput : $("input:checkbox");
targetcheckboxes.each(function () {
total12 += parseFloat($(this).next("input").val(), 10) * 1;
});
$("#total12").val(total12.toFixed(3));
}
});
$(window).load(function () {
$(document).ready(function () {
$("select").on('change', function () {
var dept_number = $(this).val();
var price = $(this).find(':selected').data('price');
var selected = $(this).find('option:selected').text();
if (selected == "INR") {
$(this).closest('table').find('.total1').val($(this).closest('table').find('.total').val());
} else {
$(this).closest('table').find('.total1').val((($(this).closest('table').find('.total').val() * price) / $(this).closest('table').find('.inrvalue').val()).toFixed(3));
}
$(this).closest('table').find('.price_unit').val(($(this).closest('table').find('.total1').val() / $(this).closest('table').find('.qty').val()).toFixed(3));
});
});
}); //]]>
In the fiddle you can see the last field, that is margin field. And extreme down you can see the Grand Total. Page Load its showing NaN..
you simply need to check input value next to checkbox whether its isNaN() or notDEMO There are many bugs like if you enter Text in Total colum you get NaN in textbox beside checkbox as well in Grandtotal since your updating it after change in input you need to validate the textbox on change
targetcheckboxes.each(function () {
var temp=$(this).next("input").val();
if(temp){
total12 += parseFloat(temp, 10) * 1;
}
});
$("#total12").val(total12.toFixed(3));
UPDATED ANSWER
So I was wrong, after some more testing its just that your first 3 readonly checkboxes don't have value=0.000 as an attribute.
As they are text inputs, javascript doesn't automatically assume that an empty input is equal to 0.
just add value=0.000 to the first three checkboxes
INCORRECT OLD ANSWER
In your targetcheckboxes.each() loop, your expression:
total12 += parseFloat($(this).next("input").val(), 10) * 1;
is causing the problem.
next("input") will match any type of input including text inputs. somewhere along the line you are concatenating a string to your total12 variable and hence the final value of total12 can not be parsed to a float.
I think you should use
parseInt(yourvalue);
parseFloat(yourvalue).toFixed(2);
whenever you are calculating something using js
I have a math game that works partially. What I need to have happen is to take the values of the divs (one is x and the other is y), type in the answer of those two multiplied, be able to submit it and refresh to solve another.
Any help would be much appreciated!
http://jsfiddle.net/justinw001/Mttw6/11/
<script type="text/javascript">
function myFunction() {
score = 0;
var number = document.getElementById('inputElement').value;
questionAmount = number;
for(i = 0; i < questionAmount; i++) {
var x = Math.floor(Math.random() * 13);
var y = Math.floor(Math.random() * 13);
$('#input1').text(x);
$('#input2').text(y);
<!-- question = prompt('What is ' + x + ' * ' + y + ' = ?'); -->
question = document.getElementById('answer').value;
if(question == null || isNaN(question)) {
break;
}
if(question == x * y) {
score++;
}
}
alert('You got ' + score + ' out of ' + questionAmount + ' correct.');
}
</script>
Try to bind the process with your buttons. Clicking the left button, produce the questions.
And Clicking the right one, verify the answer.
Demo: Fiddle
var score = 0;
var questions = [];
// Generate questions
$('#gen').click(function () {
score = 0;
questions = [];
var questionAmount = parseInt($('#inputElement').val(), 10);
for (var i = 0; i < questionAmount; i++) {
var q = {
x: Math.floor(Math.random() * 13),
y: Math.floor(Math.random() * 13)
};
questions.push(q);
}
nextQuest(questions.pop());
});
// Verify the answer
$('#sub').click(function () {
var ans, x, y;
if (questions.length >= 0) {
ans = parseInt($('#answer').val(), 10);
x = parseInt($('#input1').text(), 10);
y = parseInt($('#input2').text(), 10);
if (ans === x * y) {
score++;
nextQuest(questions.pop());
} else {
alert('err');
}
}
});
var nextQuest = function (q) {
if (q) {
$('#input1').text(q.x);
$('#input2').text(q.y);
$('#answer').val('');
$('#inputElement').val(questions.length);
} else {
$('#input1, #input2').text('');
$('#answer, #inputElement').val('');
alert(score);
}
};