Addition is not working in JavaScript
One or both of the variables is a string instead of a number. This makes the +
do string concatenation.
'2' + 2 === '22'; // true
2 + 2 === 4; // true
The other arithmetic operators / * -
will perform a toNumber
conversion on the string(s).
'3' * '5' === 15; // true
A quick way to convert a string to a number is to use the unary +
operator.
+'2' + 2 === 4; // true
...or with your variables:
+x + +y
Addition On javascript Not working when new row is added
You have to use .on()
for the event to work on dynamically created element. This will allow the event to work on the elements those are added to the body at a later time.
Change:
$(".add").click(function() {
To
$(".container").on("click", ".add", function() {
You can use .map()
and reduce()
to calculate the total. Try the following way:
var str = "";var counter = 0;var total = 0;
$(document).ready(function() { $(".container").on("input", ".amount, .penalty", function() { var tArr = $(".amount, .penalty").map(function(i,el){ return Number($(this).val()); }).get(); total = tArr.reduce((a,c) => a+c,0); //console.log(total); $("#total").html(total); });
$(".container").on("click", ".add", function() { str ="<div class='form-group row' >" +"<label class='col-xs-3 col-form-label mr-2'>Reason</label>" +"<div class='col-xs-9'>" + "<input type='text' class='form-control' id='reason"+counter+"' name='reason'>" +"</div>"
+"<label class='col-xs-3 col-form-label mr-2'>Amount</label>" +"<div class='col-xs-9'>" + "<input type='text' class='form-control amount' id='amount"+counter+"' name='amount'>" +"</div>"
+ "<label class='col-xs-3 col-form-label mr-2'>Penalty</label>" +"<div class='col-xs-9'>" +"<input type='text' class='form-control penalty' id='penalty"+counter+"' name='penalty'>"
+"</div>"
+ "<div class='col-xs-9'>" + "<button type='button' class='add'>+</button>" + "<button type='button' class='remove'>-</button>" + "</div>" + "</div>"; counter++; $("#customsAdd").append(str); });
$(".container").on("click", ".remove", function() { if($(".form-group.row").length > 1){ // remove only if there is more than one element $(this).closest('.form-group.row').remove(); $(".amount, .penalty").trigger("input"); } });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script><div class="container"> <!-- <select class="form-control col-md-6"> <option value="1">Customs</option> <option value="2">VAT</option> <option value="3">Excise</option> <option value="4">Others</option>
</select>-->
<!--div for customs!--> <div class="form-group row" id="forCustoms"> <label class="col-xs-3 col-form-label mr-2">Reason</label> <div class="col-xs-9"> <input type="text" class="form-control" id="reason" name="reason"> </div>
<label class="col-xs-3 col-form-label mr-2">Amount</label> <div class="col-xs-9"> <input type="text" class="form-control amount" id="amount" name="amount"> </div>
<label class="col-xs-3 col-form-label mr-2">Penalty</label> <div class="col-xs-9"> <input type="text" class="form-control penalty" id="penalty" name="penalty"> </div>
<div class="col-xs-9"> <button type="button" class="add">+</button> <button type="button" class="remove">-</button> </div> </div> <!--div for customs! ends--> <div id="customsAdd"></div> <div class="col-md-12"> Total : <p id="total"></p> </div>
</div>
Addition is not working properly in Reactjs
So there's a few things you can do to avoid render issues here. First, you should avoid calling anything on the document
because a rerender will remove your previous actions against it.
If you have all your buttons respect the state, then you can enable/disable them easily:
class Slides extends React.Component {
constructor() {
super();
this.state = {
n: 0,
};
}
restart = () => {
this.setState({
n: 0,
});
};
previous = () => {
this.setState({
n: this.state.n - 1,
});
};
next = () => {
this.setState({
n: this.state.n + 1,
});
};
render() {
return (
<div>
<div id="navigation" className="text-center">
<button
id="restart"
data-testid="button-restart"
className="small outlined"
onClick={this.restart}
>
Restart
</button>
<button
id="prev"
data-testid="button-prev"
className="small"
onClick={this.previous}
disabled={this.state.n === 0}
>
Prev
</button>
<button
id="next"
data-testid="button-next"
className="small"
onClick={this.next}
disabled={this.state.n === this.props.slides.length - 1}
>
Next
</button>
</div>
<div id="slide" className="card text-center">
<h1 data-testid="title">{this.props.slides[this.state.n].title}</h1>
<p data-testid="text">{this.props.slides[this.state.n].text}</p>
{console.log(this.props.slides)}
</div>
</div>
);
}
}
Also, you can check the length property of the slides prop instead of hardcoding 4 :)
js addition script not working properly
make it
function add () {
var x =parseInt(prompt("Enter a number."),10);
var y = parseInt(prompt("Enter another number."),10);
if ( !isNaN(x) && !isNaN(y) )
{
var a = x + y;
alert(a);
}
else
{
alert("One of the numbers is not valid");
}
}
you need to parse the string received from the prompt to a integer first.
Addition not working in Javascript
That happens whenever you have a string rather than a number. The +
operator performs concatenation for strings. Make sure you parse your strings to numbers using parseFloat or parseInt:
var service = document.getElementById("service");
var serviceprice = parseInt(service.options[service.selectedIndex].id, 10);
var tech = document.getElementById("tech");
var techprice = parseInt(tech.options[tech.selectedIndex].id, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
Note that parseInt
takes an argument to specify the base. You almost always want base 10
.
Subtraction operator work but Addition operator not working
You're converting both hh and zz to strings when you use .toFixed()
. If you keep them as numbers then they both work. Simply move the .toFixed()
to where you set the element text.
setTimeout(start, 1000);
var hh = 9999.9999;var num = document.getElementById('number');
function start() { setInterval(increase, 1000); }
function increase() { if (hh > 0.0001) { hh = hh - 0.0001; num.innerText = hh.toFixed(15); }}
setTimeout(startmiao, 1000);
var zz = 8888.8888;var nummiao = document.getElementById('miaonumber');
function startmiao() { setInterval(increasemiao, 1000);}
function increasemiao() { if (zz > 0) { zz = zz + 0.0001; nummiao.innerText = zz.toFixed(15); }}
<span id="number">this work</span><br /><span id="miaonumber">this doesn't work</span>
Javascript calculator addition is not working properly
The parseInt() function parses a string argument and returns an integer.
You have to assign parsed
value to your variable, like this:
first=parseInt(first);
second=parseInt(second);
Or simply,
document.write(parseInt(first)+parseInt(second));
See reference here.
var first = prompt("First number");var second = prompt("Second number");parseInt(first);parseInt(second);var islem = prompt("Is it +/-/* or /?");if (islem == "+" ) { document.write(parseInt(first)+parseInt(second));}else if ( islem == "-") { document.write(first-second);}else if ( islem == "*" ) { document.write(first*second);}else { document.write(first/second);}
Addition operators not working
Let me write the expression main.style.top -= 100 + '%';
in another way that means the same thing:
main.style.top -= (100 + '%' /* this is a string now */)
What happens if you -= a string from anything? The first expression that you put (main.style.top = top - 100 + '%';
) was closer to what you want but still not right. If you want to subtract 100% of the top value every time, like you said you need to do it in terms of pixels, not percent. So first you need to find how many pixels is 100 percent, which looking at your code might just be the value of main.offsetTop
for you. Then you need to subtract that value from the top value. So what you have first is close but I think you need:
var main = document.getElementById('main');
window.addEventListener('scroll', function(){
window.scrollTo(0, 0);
var top = main.offsetTop;
main.style.top -= top;
});
Why is my addition and subtraction not working?
Just wrap your operation in brackets
e.g.
console.log("The result is : " + (Number(num1) + Number(num2)));
console.log("The result is : " + (Number(num1) - Number(num2)));
Reasoning
As per operator precedence, multiplication and division works as they have higher precedence, i.e. they will be executed first. In case of addition and subtraction, the precedence is same and is operated from left to right. Hence, first the the string "The result is : "
is added to Number(num1)
and then added to Number(num2)
which result in concatenation and for subtraction, it becomes trying to subtract a number from a string, resulting in NaN
For reference, Operator precedence
Related Topics
How to Break a String Across More Than One Line of Code in JavaScript
How to Toggle an Element's Class in Pure JavaScript
How to Check If Iframe Is Loaded or It Has a Content
Set Additional Data to Highcharts Series
Jquery (Or Pure Js) Simulate Enter Key Pressed for Testing
Understanding Meteor Publish/Subscribe
Parse JSON String into a Particular Object Prototype in JavaScript
What's the Cause of the Error 'Getaddrinfo Eai_Again'
How to Change the Content of a <Textarea> with JavaScript
Javascript: Which Browsers Support Parsing of Iso-8601 Date String with Date.Parse
Cloud Firestore Case Insensitive Sorting Using Query
Typeerror: Console.Log(...) Is Not a Function
How to Set Default Homepage in Ff and Chrome via JavaScript
How to Set Multiple CSS Styles in JavaScript