Not getting the value from document.getElementById method - javascript

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.

Related

Javascript median using for

So I'm trying to learn javascript, and I want to find the median of some numbers that I insert into a prompt when I click on the button "find median".
function Media()
{
var n = prompt("number of elements?");
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
I made a test with two numbers, 1 and 2, and the median was 6, and i cant figure what i've done wrong
You should parse the result of prompt to an integer;
How to convert a string to an integer in JavaScript?
function Media() {
var n = parseInt(prompt("number of elements?"));
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
m = parseInt(m);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
Media();
<div id='rezultat' />
You should also parse the result of prompt using parseInt
var m = parseInt(prompt("insert # " + i));
s/n gives the mean of the input. If you are looking for the median, you should use an array to store the inputs and get the element(s) in the middle.

Javascript. Math.sqrt giving NaN to a positive number?

I currently have a script that takes numbers from a text area and does all sorts of calculations with them. I am having trouble with my standard deviation function because it will not output the value even though it's type is number, and it is positive (.56).
When I run this code
var variance = findVariance(array);
variance = parseFloat(variance);
alert(typeof variance);
the result is
number
And the value is .56 (which I know because when I don't use parseFloat it returns .56 as a string). So I am baffled when I run this code
alert("variance " + variance);
alert("sd" + Math.sqrt(variance));
and both alerts return
NaN
This is the code that creates the textarea, calls the function processData( which gathers the input from myTextArea into an array and then calls the function findStandardDeviation) I can post the variance function as well if you'd like.
<textarea id="myTextArea" rows = "7" cols = "50"></textarea><br>
<button onclick="processData()">Done</button>
<p id = "sd"></p>
<script type = "text/javascript">
var standard_deviation = 0;
var sdOutput = document.getElementById('sd');
function processData()
{
var arrayOfLines = document.getElementById('myTextArea').value.split('\n');
findStandardDeviation(arrayOfLines);
}
This is the most reducible form of my script I could manage:
var mean = 0;
var median = 0;
var count = length;
var mode = 0;
var variance = 0;
var standard_deviation = 0;
var meanOutput = document.getElementById('mean');
var countOutput = document.getElementById('count');
var sumOutput = document.getElementById('sum');
var varianceOutput = document.getElementById('variance');
var sdOutput = document.getElementById('sd');
function processData() {
var arrayOfLines = document.getElementById('myTextArea').value.split('\n');
var sum = findSum(arrayOfLines);
findMeanOutput(arrayOfLines, sum);
findVariance(arrayOfLines);
findStandardDeviation(arrayOfLines);
}
function findSum(array) {
var count = array.length;
var sum = 0;
for (var a = 0; a < array.length; a++) {
sum += parseInt(array[a]);
}
countOutput.innerHTML = "Count: " + array.length;
sumOutput.innerHTML = "Sum: " + JSON.stringify(sum);
sum = parseInt(sum);
return sum;
}
function findMean(array) //Used for finding mean and then returning it
{
var sum = 0;
for (var a = 0; a < array.length; a++) {
sum += parseFloat(array[a]);
}
mean = sum / array.length;
return mean;
}
function findMeanOutput(array, sum) //finds mean and then establishes it as the mean for users input
{
mean = sum / array.length;
meanOutput.innerHTML = "Mean: " + mean;
}
function findVariance(array) {
var mean = findMean(array);
var variance = "Variance: " + findMean(array.map(function(num) {
return Math.pow(num - mean, 2);
})).toFixed(2);
varianceOutput.innerHTML = "Variance: " + variance;
return variance;
}
function findStandardDeviation(array) {
var variance = findVariance(array);
variance = parseFloat(variance);
alert(typeof variance);
alert("variance " + variance);
alert("sd" + Math.sqrt(variance));
sdOutput.innerHTML = "Standard Deviation: " + Math.sqrt(variance).toFixed(2);
}
<html>
<head>
</head>
<body>
<p> Please enter a series of numbers, each separated by a new line.<br>
<p>
<textarea id="myTextArea" rows="7" cols="50"></textarea><br>
<button onclick="processData()">Done</button>
<p id="mean"></p>
<p id="count"></p>
<p id="sum"></p>
<p id="variance"></p>
<p id="sd"></p>
</body>
</html>
.56 is not an integer, so you shouldn’t use parseInt. parseFloat is the function you’re looking for. Or much simpler: Number.
Try For this:
in your case .56 is float, so use parseFloat
parseInt - convert string to integer number, if you will float to it then it will give 0,
parseFloat - return number to float,
I was appending the string "Variance: " to the variance variable alongside the actual variance, which when converted to a float still resulted in a NaN. I solved it by swapping this:
variance = parseFloat(variance);
out with this:
variance = parseFloat(+variance.match(/[\d.]+/)[0]);

How to convert a number where I replaced the dot with a comma from a string back to a decimal number

I have an input field where users can enter decimal numbers by using a Dot or a comma ( Example: 79,99 or 79.99 ) . When users enter the number with a comma I replace it with a dot ( this number is then sent to a remote server for verification) . Now I would like to display the number after the user enters it in the footer using toFixed(2) function to display only the first two decimal numbers. I cant get it to work , because after converting it back to a number using ParseFloat the 2 decimals after the comma disappear.
Example:
User enter in the input field : 79,99 which is then set into the variable totalAmount:
$('#amount-1').keyup(function() {
getRefundAmount(1); // This function calls the calcTotalAmount function
})
function calcTotalAmount() {
console.log('calcTotalAmount');
var totalAmount = 0;
var totalRefund = 0;
var rowAmount = 0;
var rowRefund = 0;
for(var i = 1; i < 4; i++ ) {
rowAmount = parseFloat($('#amount-' + i).val());
rowRefund = parseFloat($('#result-' + i).text());
if(!isNaN(rowAmount)) {
totalAmount += rowAmount;
totalRefund += rowRefund;
}
}
var toPay = totalAmount-totalRefund;
totalAmount = totalAmount.toString().replace(/\,/g, '.');
totalAmount = parseFloat(totalAmount).toFixed(2);
$('#footer-refund').text(totalRefund)
$('#footer-total').text(totalAmount)
if (totalAmount == '') {
$('#footer-total').text("0.00");
}
}
The Result displayed in the footer is : 79.00 instead of 79.99
I tried your code in jsfiddle and got an error on the ".toFixed(2)"
After changing it a bit i could prevent the error.:
$(function() {
var totalAmount = '79,99';
totalAmount = parseFloat( totalAmount.toString().replace(/\,/g, '.'));
totalAmount = totalAmount.toFixed(2);
$('#footer-refund').text(totalAmount)
});
https://jsfiddle.net/jkrielaars/2gb59xss/1/
It seems like the code you've given works just fine but there are some fixes you could apply :
totalAmount = ("" + totalAmount).replace(/\,/g,'.');
totalAmount = parseFloat(totalAmount);
//use toFixed only if you don't restrict input to 2 decimals, but I'd recommend restricting input otherwise you'll encounter rounding issues
Btw, you do $('#footer-refund').text(totalRefund.toFixed(2)), shouldn't it be $("#footer-refund").text(totalAmount) (not sure why you use toFixed here too) ?
Thanks for all the help :
solution is as follows : I have to check it in the for loop already and replace it there.
for(var i = 1; i < 4; i++ ) {
if(!$('#amount-' + i).val()){continue;}else{
rowAmount = parseFloat($('#amount-' + i).val().toString().replace(/\,/g,'.'));
rowRefund = parseFloat($('#result-' + i).text());
if(!isNaN(rowAmount)) {
totalAmount += rowAmount;
totalRefund += rowRefund;
}
}
}

Checking random number variable against Javascript array values for match, not working

For the sake of learning (I am very much a beginner), I am trying to write a function with that will generate random numbers according to three user inputed variables. The user can input how many random numbers to generate
var count = 10;
which numbers to avoid generating (seperated by commas)
var doNotInclude = (document.getElementById("doNotIncludeInput").value).split(",");
and what the highest number possible should be
var highestNumber = 10;
In theory, if the user inputed "1,2" for the doNotInclude variable, the function should create an array containing those two numbers and then each time it generates a random number, check it against the array to see if the number it generated is one of the numbers it isn't supposed to generate.
Unfortunately, it doesn't work. It creates the array as it should which I verified via console.log(), but it will still generate the numbers it isn't supposed to. Here's the full script:
document.getElementById("button").onclick = function() {
var total = 0,
average = 0,
random = 0,
count = parseInt(document.getElementById("countInput").value),
doNotInclude = document.getElementById("doNotIncludeInput").value).split(","),
highestNumber = parseInt(document.getElementById("highestNumberInput").value);
document.getElementById("text1").innerHTML = "";
for (var i = 0; i < count; i++) {
var proceed = false;
for (random = Math.floor(((Math.random()) * (highestNumber + 1))); proceed == false;) {
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
}
document.getElementById("text1").innerHTML = document.getElementById("text1").innerHTML + "<br />" + (i + 1) + ". " + random;
total = total + random;
if (i == (count - 1)) {
total / count;
document.getElementById("text").innerHTML = "Mean average = " + (Math.round(total / count));
}
}
}
The part that isn't working
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
the indexOf function, is something I read about on here, but I guess I don't fully understand it. By my understanding, it should check to see if any of the array values are the same as the random variable, and if not, then return "-1" and execute my code. It doesn't seem to be doing that though. I am super confused...would love some help. Is it possible the array is storing the numbers as strings instead of integers, and that is the problem?
Your if statement doesn't work because of coercion.
===-1
The array doNotInclude contains strings, but random is an integer value, === always compares value and type both.
You should either use ==. Or have the both types same.
Try this Fiddle
HTML
Count: <input id="countInput" value="10" /><br />
Do not include: <input id="doNotIncludeInput" value="0,1,2,3,4,5" /><br />
Highest Number: <input id="highestNumberInput" value="10" /><br />
<br />
<button type="button" id="button">Click to Run!</button><br />
<br />
Results:<br />
<div id="text1"></div>
Js
document.getElementById("button").onclick = function() {
var currentCount = 0;
var randomNumbers = [];
var count = parseInt(document.getElementById("countInput").value);
var doNotIncludeInput = document.getElementById("doNotIncludeInput").value.split(",");
var highestNumberInput = parseInt(document.getElementById("highestNumberInput").value);
var resultsElement = document.getElementById("text1");
resultsElement.innerHTML = "";
while(currentCount < count) {
var random = -1;
while(random === -1){
random = Math.floor((Math.random()) * (highestNumberInput + 1));
for(var i in doNotIncludeInput) {
if(parseInt(doNotIncludeInput[i]) === random){
random = -1;
}
}
if(random !== -1){
randomNumbers.push(random);
}
}
currentCount += 1;
}
resultsElement.innerHTML = randomNumbers.join(', ');
}

issue to sum fields

This is a basic html/javascript code, but I am having issues getting the sum of all fields.
(The are 50 fields in the original project, but now I just leave 5)
If the field is blank, it just has to ignore it, and add only those with filled fields.
HTML code:
value1:<input type="text" id="total_1" ><br>
value2:<input type="text" id="total_2" ><br>
value3:<input type="text" id="total_3" ><br>
value4:<input type="text" id="total_4" ><br>
value5:<input type="text" id="total_5" ><br>
total:<input type="text" id="totalresult" >
<button type="button" onclick="getTotal(); return false;">Get total</button>
Javascript:
function getTotal() {
var sum;
for (i = 1; i <=5 ; i++) {
var total = document.getElementById('total_' + i.toString()).value;
if (total != '') {
sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
}
I don't know why my code is isn't working.
Here is my Fiddle
The first time your code runs, sum will be undefined.
Initialize
var sum = 0;
Also to make it work in the fiddle, you need to change
the onLoad on the left top to 'No wrap - in '
You need to do two things. 1, initialize sum to zero. 2, check the input values for not being a number.
function getTotal() {
var sum = 0;
for (i = 1; i <= 5; i++) {
var total = document.getElementById('total_' + i).value;
if (!isNaN(parseFloat(total))) sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
jsFiddle example
I don't know why your fiddle can't figure out to make getTotal a global. But your main problem is that sum is undefined as start. This will result in NaN (Not a Number) :
var sum;
sum = 1 + sum; // NaN
....
sum = 1 + undefined; // NaN
sum = 1 + NaN; // NaN
Demo at jsbin.com
You should set sum equal zero at first:
var sum = 0;
for ( ... ) { ...
Working demo as adrianp pointed out: It would probably be more clear if you uploaded the working code to jsbin.
You haven't defined sum variable so javascript takes that as NaN, which means Not a Number. You need to initilaize it to set it right.
function getTotal() {
var sum = 0;
for (i = 1; i <=5 ; i++) {
var total = document.getElementById('total_' + i.toString()).value;
if(isNaN(total) || total.indexOf(' ') == 1) {
alert("Please type a number");
document.getElementById("totalresult").value = "I cant sum alphanumerics";
return false;
}
if (total != '') {
sum = parseFloat(total) + sum;
document.getElementById('totalresult').value = sum;
}
}
}
FIDDLE
Use IsNumeric function to check if the input field has a valid number. See: Validate decimal numbers in JavaScript - IsNumeric()
Here is my suggestion to improve the code inside your for loop:
var elementValue = document.getElementById('total_' + i).value
IsNumeric(elementValue) ? elementValue : elementValue = 0;

Categories