I have started learning Javascript recently and I am trying to create a script used to calculate a set of user input numbers. I use a function to give a prompt to the user and get the value from the user. Then I use another function to take the prompt input and add it to my own value. But the result is always a set of continuous values. My code is the following one, please help.
<body>
<p>
Click below to calculate a value.
</p>
<button onclick='myfunc()'>Calculate</button>
<p id='demo'></p>
<script type='text/javascript'>
function getvalue() {
var foo = prompt('Enter a number');
return(foo);
}
function myfunc() {
var a = getvalue();
var x = a + 2;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
Use parseInt()
https://www.w3schools.com/jsref/jsref_parseint.asp
Either you can use it inside your function or outside like following.
function getvalue() {
var foo = prompt('Enter a number');
parseInt(foo); //Parse string to integer
}
OR
function myfunc() {
var a = parseInt(getvalue()); //Parse string to integer
var x = a + 2;
document.getElementById("demo").innerHTML = x;
}
Dont forget to do validation (to make sure it's an integer) of the prompt output in your program !
All inputs from prompt are treated as a string. You need to specify the var type to be a number (it can be an integer - int - or decimal - double or float). To parse the value just use parseInt, parseDouble, parseFloat.
Difference between double and float is the decimal accuracy.
function getvalue() {
var foo = prompt('Enter a number');
return parseInt(foo); // also try parseDouble for decimal values
}
function myfunc() {
var a = getvalue();
var x = a + 2;
document.getElementById("demo").innerHTML = x;
}
<button onclick="myfunc()">Test</button>
<br/>
<p>
The Value is: <span id="demo"></span>
</p>
You can convert your string into a number with the + operator :
function getvalue() {
// v Here is where the magic is taking place
var foo = +prompt('Enter a number');
return(foo);
}
function myfunc() {
var a = getvalue();
var x = a + 2;
document.getElementById("demo").innerHTML = x;
}
Related
var binaryValue = document.getElementById('binary');
function binaryToDecimal() {
var val = binaryValue.value;
var result = 0;
var i = val.length-1;
var j = 0;
while (i > -1) {
var y = (Number(val[i])) * (2 ** [j]);
result += y;
i--;
j++;
console.log(y);
}
decimalValue.value = result;
console.log(binaryValue.value);
}
Using the code above, I tried to obtain a value from an input field and do a calculation to convert it to a decimal number. But it doesn't obtain the input value. I tried several times and I am unable to figure out it.
This is how you get a value from an input field:
var binaryValue = document.getElementById('binary');
function binaryToDecimal() {
var NumValue = binaryValue.value
console.log("input value: " + NumValue);
//this is how you convert a binary number to decimal
console.log("binary number: " + (NumValue >>> 0).toString(2));
//this is how you convert an decimal number to binary
console.log("decimal number: " + parseInt(NumValue, 2));
}
<input type="text" id="binary" placeholder="insert value"/>
<button type="button" onclick="binaryToDecimal()">Show value</button>
Use this example to fix your code.
I also added ways to convert to and from binary numbers.
I have some problem with my js code which when I run the code it show me a NaN error, I have a function that calculate something.
Example:
<p id = "total "></p>
total = num1 *num2;
document.getElementById("total").innerHTML = total;
And it works fine but when I create a new function to calculate the discount
var price = document.getElementById("total").value;
discount = total *0.10;
It shows a NaN, I tried a lot of solution but it is still not working.
Can you help me?
I think you have a concept mistake, if the value is a HTML value, i mean, is inside of
<p id="this_is_the_element">123456789</p>
You can get that value with javascript using the
var number = document.getElementById('this_is_the_element').innerHTML
now the number variable will have inside "123456789" as a STRING
But if you are using an input you should use
var number = document.getElementById('this_is_the_element').value
Now, try this. First try to avoid the parseInt, instead use Number.
Define a function
var discount = function(){
var price = Number(document.getElementById("total").innerHTML);
return price*0.1;
}
If you want to do it on new sintax use this
const discount = () => {
const price = Number(document.getElementById("total").value);
return price*0.1;
}
There are few issues in your code:
There is no value property of p element. To access the text in p element, you can use either textContent or innerText.
By default the text is of type string. Multiplying string with number gives you NaN. You have to convert that to number before doing any arithmetic operation.
var num1 = 5;
var num2 = 20;
var total = num1 *num2;
document.getElementById("total").textContent = total;
var elTotal = Number(document.getElementById("total").textContent);
var discount = elTotal * 0.10;
console.log(discount)
<p id = "total"></p>
When you pull the value, it's a String, and JavaScript for the most part will automatically do type conversion, but you can always wrap it in parseInt to force it to be a Number.
discount = parseInt(total) * 0.10;
You can also always run typeof total to verify if total is a Number or String, and you can run console.log(total) to visually verify the contents.
Also, your document.getElementById("total") references a paragraph element, which doesn't have .value property, so you should use innerText to get its value instead.
Demo
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
button1.addEventListener('click', function() {
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
total = parseInt(num1) * parseInt(num2);
document.getElementById("total").innerText = total;
});
button2.addEventListener('click', function() {
var total = document.getElementById("total").innerText;
discount = parseInt(total) * 0.10;
document.getElementById('discount').innerText = discount;
});
<input type="text" id="num1" /><br>
<input type="text" id="num2" /><br>
<button id="button1">Add</button>
<p id="total"></p>
<button id="button2">Discount</button>
<p id="discount"></p>
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
My code is to find a random number between two numbers, In context they will be frequencies. But im stuck not displaying the correct values? Thanks in advance for any help.
function noteFinder() {
var x = document.getElementById("userInput").value;
var i = Math.random() * ((x*2) - x);
document.getElementById("demo").innerHTML= i + x;
document.getElementById("demo2").innerHTML= x;
}
So instead of showing "demo" as x + i it is only outputting i. Here is the html if that could be something as well as the codepen project [https://codepen.io/bazookajo66/pen/MPYVJW]
<input type="number" id="userInput"=> </input>
<button onclick="noteFinder()">Submit</button>
<p id="demo"></p>
<p id="demo2"></p>
Note that .value is always a string; the easiest way to convert a string to a number with Javascript is with a plus +:
function noteFinder() {
var x = +document.getElementById("userInput").value;
var i = Math.random() * x;
document.getElementById("demo").innerHTML = i + x;
document.getElementById("demo2").innerHTML = x;
}
Im working on a simple conversation form, where I need to input dimensions ex. 12x24x36 inches to 304.8 x 609.6 x 914.4 mm.
My problem is I don't know how to compute convert those numbers separately.
I manage to remove the x but all the numbers merge.
Thanks, I hope you understand me.
here is my sample code
HTML
<h4>Dimensions</h4>
<label>inches <input id="number1"></label>
<label>mm <input id="number2"></label>
<button type="button" onclick="myFunction()">convert</button>
JS
function myFunction() {
var inches = document.getElementById("number1").value;
var removex = inches.replace(/x/g,"");
var input = parseInt(removex);
document.getElementById("number2").value = input
}
CODEPEN
https://codepen.io/anon/pen/yPpmej
If you have a string like:
var str = '304.8 x 609.6 x 914.4 mm'
You can use split() and parseFloat() to get an array of numbers with:
var str = '304.8 x 609.6 x 914.4 mm'
var numbers = str.split('x').map(parseFloat)
console.log(numbers)
You just need to know your input format so you can adjust for other variations.
parseFloat() will ignore any non-numeric characters after the numbers so it works well for stripping units.
If your receiving "12x24x36" as input(string) then for complete desired result update your function as below:-
function myFunction() {
var inches = document.getElementById("number1").value;
var inchesArr = inches.split("x");
var mmArr = inchesArr.map(function(i) {
return parseFloat(i) * 25.4;
});
var mmString = mmArr.join("x");
document.getElementById("number2").value = mmString;
}
EXPLANATION
You can convert your input example 12x24x36 into an array via str.split('x'), then do the math conversion from inch to millimeters (x inches * 25.4) and push those back into a new array of millimeters values. Then you can rejoin those values with an x via str.join('x') and put them back into your document. Here's what it looks like.
SCRIPT
function myFunction() {
var inches = document.getElementById("number1").value.split('x');
var millimeters = [];
for (var i = 0; i < inches.length; i++) millimeters.push(parseInt(inches[i]*25.4));
document.getElementById("number2").value = millimeters.join('x');
}
CODEPEN
https://codepen.io/anon/pen/KyZOYb
I've used var.split("_"); here. Example of a value I'm trying to get would be: 2_25000
However, below code results a NaN value.
function calculateTotal() {
var room_type_id = document.getElementById('room_type_id').value;
var room_type_cost = room_type_id.split("_");
var meal_type_id = document.getElementById('meal_type_id').value;
var meal_type_cost = meal_type_id.split("_");
var bed_type_id = document.getElementById('bed_type_id').value;
var bed_type_cost = bed_type_id.split("_");
var ext_beds_id = document.getElementById('ext_beds_id').value;
var reservation_duration = document.getElementById('reservation_duration').value;
document.getElementById('total_amount').value = ( Number(room_type_cost[1]) + Number(meal_type_cost[1]) + Number(bed_type_cost[1]) + Number(ext_beds_id) ) * Number(reservation_duration);
}
you may use number() function or parseInt() function but remember to also pass the base 10 second parameter in parseInt("23", 10), also you can prefix + symbol to convert it to integer.
for i.e., +"23" + 2
Try this one............
change
Number()
to
parseInt()