I have an HTML table which contains a value as well as a checkbox every row.
When I click on the checkbox, it activates a script which adds this value in another fixed cell. If the checkbox is checked, it adds the number, if it is unchecked, it subtracts the number.
function val_sel_achat(val, id)
{
if (document.getElementById(id).checked)
{
document.getElementById('res_achat').innerHTML += val;
}
else
{
document.getElementById('res_achat').innerHTML -= val;
}
}
It's mostly working well, except that it seems to concatenate chains rather than add numbers.
So if I check a box with val = 100, then uncheck it, it displays 100, then 0, which is alright.
But if I check two different boxes, like 100 and 25, it displays 10025.
How would I change my code so it displays 125 instead?
Thanks.
function val_sel_achat(val, id)
{
var x = document.getElementById('res_achat').innerHTML;
if (document.getElementById(id).checked)
{
document.getElementById('res_achat').innerHTML = parseFloat(x) + val;
}
else
{
document.getElementById('res_achat').innerHTML = parseFloat(x) - val;
}
}
Use .parseFloat()
function val_sel_achat(val, id) {
var inner = document.getElementById('res_achat').innerHTML;
if (document.getElementById(id).checked) {
document.getElementById('res_achat').innerHTML = parseFloat(inner) + parseFloat(val);
} else {
document.getElementById('res_achat').innerHTML = parseFloat(inner) - parseFloat(val);
}
}
A sample working without checkbox fiddle
Related
I'm new to coding and I built a Javascript calculator, but I can't get the display to clear after Im done with one calculation. Instead, the result of the first calculation goes into the input for the second calculation. For eg if I do 3+5 it'll give me 8, but if I then press 4, the display says 84 which is why its a problem. I can clear the screen via the clear button but it gets tedious after every single calculation. Thank you.
//select all the buttons
const buttons = document.querySelectorAll('button');
//select the <input type="text" class+"display" disabled> element
const display = document.querySelector('.display');
//add eventListener to each button
buttons.forEach(function(button) {
button.addEventListener('click',calculate);
});
//calculate function
function calculate(event) {
//current clicked buttons value
var clickedButtonValue = event.target.value;
if(clickedButtonValue === '=') {
//check if the display is not empty then only do the calculation
if(display.value !== "") {
//calculate and show the answer to display
display.value = eval(display.value);
}
//if any key except "=" pressed again clear display
button.addEventListener('click',clearDisplay);
} else if (clickedButtonValue === 'C') {
//clear everything on display
display.value = "";
} else {
//otherwise concatenate it to the display
display.value += clickedButtonValue;
}
}
function clearDisplay(clickedButtonValue) {
if(clickedButtonValue !== "=") {
display.value = "";
}
}
You can have a variable that keeps track of the calculated state. If it has been calculated, clear the display and reset the state
var calculated = false;
function calculate( event ){
var clickedButtonValue = event.target.value;
if ( calculated ) {
display.value = "";
calculated = false;
}
if(clickedButtonValue === '=') {
if(display.value !== "") {
//calculate and show the answer to display
display.value = eval(display.value);
calculated = true;
}
}
// the rest of your logic here
}
var buttons = document.querySelectorAll('.btn');
var display = document.getElementById('display');
buttons.forEach(function (element, index) {
element.addEventListener('click', addToScreen, answer);
});
function addToScreen() {
var val = this.getAttribute('value');
if (val == '=') {
answer();
}
console.log(val);
display.value += val;
}
function answer() {
val = display.value;
val = eval(val);
display.value = "";
display.value += val;
}
Hi All,
so these are my two functions that display and compute the calculation for the calculator.
however there are a couple of problems I am running. the first is that when a calculation is performed the out is a number with an equal sign for eg. 8*8 the display would be 64=. how can I get rid of the "=" sign.
second problem is with my ifval=='=' statement. The statement causes the program to jump to the answer function which has eval(val) statement. however if a user enters "=" as the first input/second this would display undefined on the display calculator screen. how can I fix these two issues?
Thanks
Return after you call answer() inside the addToScreen function
function addToScreen() {
var val = this.getAttribute('value');
if (val == '=') {
answer();
return;
}
console.log(val);
display.value += val;
}
I've got an issue with jQuery's autocomplete. What I am trying to do is show a suggestions list based on input. So, for instance, on input class="font" I want to have a list of font sizes and on input class="color" to have a list of color predictions.
Here is what I have:
function suggestions(input, element) {
var suggestions = [];
if (element.hasClass("color") !== -1) {
var i = 0;
while (i < 100) {
suggestions.push("color" + i.toString()); // for testing purpose
i++;
}
} else {
var nr = 1;
while (nr < 1025) {
suggestions.push(nr.toString() + "px");
nr = nr + 1;
}
}
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
var counter = 0;
var filteredArray = $.map(suggestions, function (item) {
if (item.startsWith(request.term) && counter < 10) {
counter = counter + 1;
return item;
} else {
return null;
}
});
response(filteredArray);
},
autoFocus: true
});
}
The thing is, it works perfectly when I test it for inputs having any class except 'color'. When it detects a class with 'color', it will build the suggestions array accordingly but will refuse to get into the anonymous function inside autocomplete - source. Which is odd to me, 'cause the array is always constructed and the autocomplete should always be hit.
Any ideas?
Thanks!
jQuery's .hasClass() returns boolean value, so you code should look like:
if (element.hasClass("color")) { ... }
Try this JSFiddle (type symbol "c")
This is the code that I am currently using:
<script>
$(".lk").click(function(){
$(this).find("#lke").html(function(i, val) { return val*1+1 });
});
$(".lk").click(function(){
$(this).find("#lke").html(function(i, val) { return val*1-1 });
});
</script>
When the user clicks on the button, the value of #lke increases by 1. When he clicks again, the value decreases by 1. The code that I am currently using does not work so how would I fix this?
You can use an external var to decide if you have to increment o decrement the value
<script>
var increment = true;
$(".lk").click(function(){
var lke = $(this).find("#lke"),
value = parseInt(lke.html()) || 0;
lke.html( increment ? value + 1 : value - 1);
increment = !increment;
});
</script>
Your code doesn't work because you assign two events for every click - one which increases the value and one which decreases it, so nothing happens.
You could use an external variable such as toAdd to determine which action to do:
var toAdd = 1;
$(".lk").click(function(){
newValue = oldValue + toAdd;
toAdd *= -1;
...
});
You put two call of the same object, try this instead
<script>
var val = 0; // Put the original value
var negative = false;
$( document ).ready(function() { // You need to declare document ready
$(".lk").click(function(){
val = val + ((negative) ? -1 : 1); // Change if its positive or negative
negative = (negative) ? false : true;
$("#lke").text(val); // Adjust the html ?
});
});
</script>
Try something like this:
$(".lk").click(function() {
if ($(this).hasClass('clicked')) {
$(this).removeClass('clicked'));
$(this).find("#lke").html(function(i, val) { return val*1-1 });
} else {
$(this).addClass('clicked');
$(this).find("#lke").html(function(i, val) { return val*1+1 });
}
});
You could also use a data attribute instead of checking for a class aswell.
Or use toggleClass().
$(".lk").click(function() {
if ($(this).hasClass('clicked')) {
$(this).toggleClass('clicked'));
$(this).find("#lke").html(function(i, val) { return val*1-1 });
} else {
$(this).toggleClass('clicked');
$(this).find("#lke").html(function(i, val) { return val*1+1 });
}
});
I have the following code:
function ViewModel() {
var self = this;
self.deckareax = ko.observable(0);
self.deckareay = ko.observable(0);
self.calculatedarea = ko.observable(20);
self.deckareax.subscribe(function () {
if (self.deckareax() == 0 || deckareay == 0) {
self.calculatedarea(0);
} else {
self.calculatedarea(self.deckareax() * self.deckareay());
}
}
);
self.deckareay.subscribe(function () {
console.log("deckareay " + self.deckareay())
if (self.deckareax() == 0 || self.deckareay() == 0) {
self.calculatedarea(0);
} else {
self.calculatedarea(self.deckareax() * self.deckareay());
}
}
);
self.deckareamxm = ko.computed({
read: function () {
return self.calculatedarea();
},
write: function (value) {
self.calculatedarea(value);
if ((self.deckareax() * self.deckareay(0)) != value) {
self.deckareax(0);
self.deckareay(0);
}
},
owner:self
});
}
;
ko.applyBindings(new ViewModel());
I want to be able to set the total area (deckareamxm) by either manually inputting or calcualting from entering deckareax * deckareay. If I enter a result and (deckareax * deckareay) doesn't equal total deck area x and y should be cleared.
This pretty much works however if I enter total area it clears both but also clears itself. If I then enter again total area it stays. I think it may have got to complex. Any ideas?
This jsfiddle seems to do what you want. There were a couple other bugs but I primary fixed the problem by moving the self.calculatedarea(value); to the bottom of the write function.