This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 2 years ago.
I am trying to add the multiplication result, but the result I want doesn't match, can you help me to see where the error is in my javascript code?
The results I want:
((x*10)/100)+x = ...
or ((30.000 * 10) / 100)+30.000 = 33000
but why the results i got = 300030000
var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
if( x == document.activeElement ){
var temp = x.value;
if( xstored != temp ){
xstored = temp;
x.setAttribute("data-in",temp);
calculate();
}
}
if( y == document.activeElement ){
var temp = y.value;
if( ystored != temp ){
ystored = temp;
y.setAttribute("data-in",temp);
calculate();
}
}
},50);
function calculate(){
d.innerHTML = ((x.value * y.value) / 100) + x.value ;
}
x.onblur = calculate;
calculate();
<div class="section">
<div class="container">
<h3>Calculate</h3>
<input id="x" data-in="" type="text" />
x <input id="y" data-in="" type="text" />
<hr>
<div id="d"></div>
</div>
</div>
The value of an input element is a string, so you need to convert it to a number before adding to prevent it from being treated as string concatenation. This can be done using the unary plus operator.
d.innerHTML = ((x.value * y.value) / 100) + (+x.value);
Related
This question already has answers here:
JavaScript: How to reverse a number?
(19 answers)
Closed 3 years ago.
I want to create a program which helps me find the reverse of a number. So, if I enter the number 135, it gives back 531 to me. I created the code, with the help of various online sources that confirm that my method is correct. However, I cannot seem to create a solution. I tried using a while loop in a similar fashion, as well. The output always comes out as Infinity. Is there a problem with my technique or the code.
<input type="button" value="Find the Reverse of a Number" onclick="inv()">
<script>
function inv() {
var n = prompt("Enter a number: ");
var rev = 0;
for (; input !== 0;) {
var lastDigit = input % 10
rev = rev * 10;
rev = rev + lastDigit;
input = input / 10;
}
}
</script>
check it .
var a = prompt("Enter a value");
var b, sum = 0;
var z = a;
while(a > 0)
{
b = a % 10;
sum = sum * 10 + b;
a = parseInt(a / 10);
}
alert(sum);
Try this:
function inv(){
var n = prompt("Enter a number: ").toString();
n = [...n].reverse().join("");
alert(`Reversed ${n}`)
}
<input type="button" value="Find the Reverse of a Number" onclick="inv()">
I am writing JavaScript / HTML for a project for one of my classes. I'm not sure why the JavaScript function won't execute. The first return ("result") works no problem but for some reason my program wont work for ("result2"). I pasted the function down below:
function multiplyBy(){
var x = document.getElementById("text").value;
var y = document.getElementById("text2").value;
var z = x * y;
var a = 52 * z;
var b = paraseFloat(a);
if (b > 20000) {
output = "The Salary is too little."
}
if else (b < 20000; b > 25000) {
output = "The Salary is almost enough. Let's negotiate."
}
else {
output = "This is a great salary for me."
}
return document.getElementById("result").innerHTML = "The Salary is: " + b;
return document.getElementById("result2").innerHTML = output
}
You have few issues in the code
paraseFloat is a miss type it should be parseFloat
if else (b < 20000; b > 25000) {
if else should be else if
if you want to have a range in your check you need to add logical operators like && ||
and the you need to review the logic for checking the salary i am not sure but i have changed something that "has" some sense
you can check in here
function multiplyBy() {
var x = document.getElementById("text").value;
var y = document.getElementById("text2").value;
var z = x * y;
var a = 52 * z;
var b = parseFloat(a);
if (b < 20000) {
output = "The Salary is too little.";
} else if (b >= 20000 && b < 25000) {
output = "The Salary is almost enough. Let's negotiate.";
} else {
output = "This is a great salary for me.";
}
document.getElementById("result").innerHTML = "The Salary is: " + b;
document.getElementById("result2").innerHTML = output;
}
multiplyBy();
<input type='text' name='text' id='text' value=10 />
<input type='text' name='text2' id='text2' value=10 />
<div id='result'></div>
<div id='result2'></div>
I have found couple of issues in your code but you were almost there. Let me summarize in few steps where it was wrong:
In your code if else was presented. Using else if works other way around, read further here.
Logical AND operator for defining between values for salary works differently, here you can find details. b < 20000; b > 25000 is just wrongly defined, I have corrected to have b >= 20000 && b < 25000. Solution uses && and changed a bit the condition.
In parsing to float case there was a typo in your function call, should have parseFloat instead of paraseFloat. Read further here.
Just changed from b < 20000 to b > 20000 which makes more sense in terms of text result.
And lastly, in your function there are 2 return statements, even if there is no need at all in that code. The function manipulates the DOM then it will automatically return undefined. Please find here the documentation for more details which states:
A function without a return statement will return a default value. ... For all other functions, the default return value is undefined.
And finally here is a working solution:
function multiplyBy() {
const x = document.getElementById("text").value;
const y = document.getElementById("text2").value;
const z = x * y;
const a = 52 * z;
const b = parseFloat(a);
if (b < 20000) {
output = "The Salary is too little.";
} else if (b >= 20000 && b < 25000) {
output = "The Salary is almost enough. Let's negotiate.";
} else {
output = "This is a great salary for me.";
}
document.getElementById("result").innerHTML = "The Salary is: " + b;
document.getElementById("result2").innerHTML = output;
}
<input id="text" />
<input id="text2" />
<div id="result"></div>
<div id="result2"></div>
<button onclick="multiplyBy()">Calculate</button>
Additionally it is worth to read further about when to use const, let and var.
Hope this helps!
This is suppose to return the converted number as a whole number. That part works but it doesn't turn the right conversion.
var input = prompt('Please enter your temp in fahrenheit');
function converter (){
var x = Math.round(input - 32 * 5/9);
console.log(x);
return x;
}
alert('The temp in celsius is: ' + converter());
The equation to convert Fahrenheit to Celcius is T(°C) = (°F - 32) × 5/9. You run into an order of operations issue. This should work.
var input = prompt('Please enter your temp in fahrenheit');
function converter (){
var x = Math.round((input - 32) * 5/9);
console.log(x);
return x;
}
alert('The temp in celsius is: ' + converter());
You are missing the paranthesis , which forced the operator precedence to take over the calculation.
var input = prompt('Please enter your temp in fahrenheit');
function converter() {
var x = Math.round((input - 32) * 5 / 9);
console.log(x);
return x;
}
alert('The temp in celsius is: ' + converter());
Try with this:
(input - 32) * (5 / 9);
That isn't correctly converting because of operator precedence, JavaScript operator precedence goes from highest (20) to lowest (0), Multiplication/Division has a precedence of 14 and Subtraction has a precedence of 13, so parenthesis (precedence 20) is required to mark which expression should execute first.
$(document).ready(function () {
$('#celsius').on('input', function (event) {
var celsius = $('#celsius').val();
var fahrenheit = celsiusToFahrenheit(celsius);
$('#fahrenheit').val(fahrenheit);
});
$('#fahrenheit').on('input', function (event) {
var fahrenheit = $('#fahrenheit').val();
var celsius = fahrenheitToCelsius(fahrenheit);
$('#celsius').val(celsius);
});
function celsiusToFahrenheit(celsius) {
if (celsius === undefined || celsius === null) {
return celsius;
}
var fahrenheit = celsius * 9/5 + 32;
return fahrenheit.toFixed(5);
}
function fahrenheitToCelsius(fahrenheit) {
if (fahrenheit === undefined || fahrenheit === null) {
return fahrenheit;
}
var celsius = (fahrenheit - 32) * 5/9;
return celsius.toFixed(5);
}
});
.form-group {
float: left;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="form-group">
<label>Celsius</label>
<input type="text" id="celsius"/>
</div>
<div class="form-group">
<label>Fahrenheit</label>
<input type="text" id="fahrenheit"/>
</div>
This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Closed 6 years ago.
I have created a function that takes a number in Imperial units entered into a div and converts that value to metric units in another div. Being relatively new to js, I am now realizing that a thousandths place comma separator does not come standard. I've tried to apply many of the solutions (many of them reg ex's) that I've found but none suit my needs or have worked. Simply put, I am just looking to have both divs outputted numbers have commas separating the thousandths place. Ultimately, these numbers are elevation values expressed in Feet and Meters. Any insight would be greatly appreciated... thanks!
Here is my code:
<body>
<div id="feet" onload="calculateMeter()">2120</div>
<div id="meter"></div>
<script>
var feet = document.getElementById('feet');
var meter = document.getElementById('meter');
function calculateMeter() {
if (feet.innerHTML > 0) {
meter.innerHTML = (feet.innerHTML * 0.3048).toFixed(1);
feet.toString();
feet = feet.innerHTML.replace(/(\d)(\d{3})\,/, "$1,$2.");
}
}
calculateMeter();
</script>
</body>
Here is a simple RegEx solution
function calculateMeter() {
if (feet.innerHTML > 0) {
var m = (feet.innerHTML * 0.3048).toFixed(2);
meter.innerHTML = m.replace(/\B(?=(\d\d\d)+\b)/g, ",");
}
}
It seems your problem is actually just setting the content the DOM element. Using the solution in How to print a number with commas as thousands separators in JavaScript for formatting numbers, all you need is:
function calculateMeter() {
if (feet.innerHTML > 0) {
meter.innerHTML = numberWithCommas*(feet.innerHTML * 0.3048).toFixed(1));
feet.innerHTML = numberWithCommas(feet.innerHTML);
}
}
My function:
function formatNumberWithCommasDec(d) {
d += "";
var c = d.split(".");
var f = c[1];
var a = c.length > 1 ? c[0] + '.' : '.', flag = false;
var g = f.split('').reverse(), y = 1, s = '';
for (var i = g.length - 1; i >= 0; i--) {
flag = false;
var e = g[i];
var h = (y === 3) ? s = s + e + ',' : s = s + e;
console.log(e);
if(y === 3){
y = 1;
flag = true;
} else {
y = y + 1;
}
}
if(flag){
s = s.substring(0, s.length - 1);
} else {
s = s;
}
return a + s;
}
Fiddle: https://jsfiddle.net/6f0tL0ec/1/
Update: found some problems, but everythings good now
I'd prefer to not use regex, but if needed, so be it.
I have some code and I want to take a user's input and check to make sure that it is an isbn 10. In other words it must be a 10 digit number or a 9 digit number with an x at the end (the x represents the number 10). For my purposes, I'd like to turn the users input into an array of each digit. If there is an x I'd like to change that into a 10. I am having trouble doing this! I have seen other questions that are somewhat similar and they all use regex. Like I said, I'd prefer to not use regex, but if need be...
<h1>Problem #3:</h1>
<form name= "form">
<input id= "input" name= "isbn" type="number" placeholder="Enter your ISBN-10" min="0" />
<input id= "button" type="button" name="Validate" value="Validate" />
</form>
<div id="validISBN">
Valid ISBN
</div>
<div id="invalidISBN">
Invalid ISBN
</div>
<script src="js/jquery-2.0.3.min.js"></script>
<script>
$( document ).ready(function() {
alert("Welcome to ISBN Validator!");
//Add the event listener for the validate button here
//Look at toggling the CSS display property based on the result
$("#button").click(function(){
checker(document.form.isbn.value);
});
});
var checker = function(isbn){
isbn = isbn.toString().split('');
if (isbn[9] == 'x'|| isbn[9] == 'X') {
isbn[9] = 10;
}
if (isbn.length !== 10) {
alert("invalid ISBN!" + isbn.length);
}
else{
var sum = 0;
for (var x=10; x>0; x--){
sum += x*isbn[10-x];
}
alert("FINAL!!" + sum%11);
}
}
Input: 0375726721
Output: FINAL!!0
:Works
Input:067978330X
Expected Output: FINAL!!0
Actual Output: Invalid ISBN!0
:Does not work!
var isbn = '074759582x';
if (!/^\d{9}(\d|x)$/i.test(isbn)) // validation with regexp
alert('Invalid ISBN');
else {
var arr = isbn.split('');
arr[9] = arr[9].toLowerCase() == 'x' ? 10 : arr[9]; // replacement of x by 10
// below is your summation, just performed in another way.
var total = arr.map(function(el, index, arr) {
return (index + 1) * arr[10 - index - 1];
}).reduce(function(a, b) {return a + b;});
alert(total % 11);
}
Done
var isbn = '074759582x';
Split the string into characters using split. Apply map to grab the x and convert it to 10 if necessary. Then map each character to a number
array = isbn
.split('')
.map(function(char, i) {
return i === 9 && char.toLowerCase() === 'x' ? 10 : char;
})
.map(Number)
;
The ISBN is valid if it's of length 10, and there are no NaNs in it.
valid = array.length === 10 && !array.some(isNaN);
Checksum uses reduce, as in another answer:
sum = array.reduce(function(result, v, i) {
return result + (10-i) * v;
}, 0) % 11;
Problem #3:
<form name= "form">
<input id= "input" name= "isbn" type="number" placeholder="Enter your ISBN-10" min="0" />
<input id= "button" type="button" name="Validate" value="Validate" onclick = "checker()" />
</form>
<div id="validISBN">
Valid ISBN
</div>
<div id="invalidISBN">
Invalid ISBN
</div>
<script>
function checker () {
isbn = document.form.isbn.value;
isbn = isbn.toString().split('');
if (isbn[9] == 'x' || isbn[9] == 'X') {
isbn[9] = 10;
}
if (isbn.length !== 10) {
alert("invalid ISBN!" + isbn.length);
}
else {
var sum = 0;
for (var x = 10; x > 0; x--) {
sum += x * isbn[10 - x];
}
alert("FINAL!!" + sum % 11);
}
}
</script>