How to correctly add variables? Improper outputs? - javascript

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;
}

Related

Concatenate value from textarea to another place

I have the following textarea
<textarea class="form-control" id="projectname"></textarea>
And I want to get its value and concatenate with the value inside this:
<h1 id="team_title"> Team name </h1>
So basically, after writing "china123" in my textarea I would get in my h1 the following = Team name - china123
I have tried the following:
function myFunction() {
var k = document.getElementById('team_title').innerHTML;
var m = document.getElementById('projectname').value;
var x = k.concat(" -" + m);
document.getElementById('team_title').innerHTML = x;
}
And I add it as a oninput attribute on the textarea. But the problem seems to be that after each input it gets the following
Team name - c -ch - chi - chin - china - china1 - china12 - china123
Although my desired output in the h1 tag is:
Team name - china123
Save the original prefix in the data-prefix property of h1
<h1 id="team_title" data-prefix="Team name "> Team name </h1>
Now keep appending value to the data-prefix value
function myFunction() {
var k = document.getElementById('team_title').getAttribute( "data-prefix" ); //observe the change here
var m = document.getElementById('projectname').value;
var x = k.concat(" -" + m);
document.getElementById('team_title').innerHTML = x;
}
You can split the string on the - and then concat them together
var input = k.split('-')[0];
var x = input.concat(" -" + m);
Hope this helps :)
function myFunction() {
var k = document.getElementById('team_title').innerHTML;
var m = document.getElementById('projectname').value;
var input = k.split('-')[0];
var x = input.concat(" -" + m);
document.getElementById('team_title').innerHTML = x;
}
<textarea class="form-control" id="projectname" onkeyup="myFunction()"></textarea>
<h1 id="team_title"> Team name </h1>
you must be calling the function onchange, which means everytime you type the function will concatenate, you have 2 choices:
1. make a button or an event that will concatenate AFTER the whole input.
2. save the h1 value and concatenate with that value unchanged (data-* attribute)
I wouldn't use concat for this.
The value of variable m is already converted as a string. In Javascript you can easily add these strings by using the + line.
function myFunction() {
var k = document.getElementById('team_title').getAttribute( "data-prefix" ); //observe the change here
var m = document.getElementById('projectname').value;
var x = k + ' - ' + m;
document.getElementById('team_title').innerHTML = x;
}

how to display different data type values with same variable in javascript

Issue:
When I am using same variable to hold different data types in java script,
and trying to display all values, it is not showing up all values except the last value which it holds. is there any alternate way to show up all data type values with same variable?
Script:
<script>
var x;
document.getElementById("demo").innerHTML = x;
x = 5;
document.getElementById("demo").innerHTML = x;
x = "John";
document.getElementById("demo").innerHTML = x;
</script>
Expected result:
undefined
5
John
Actual result:
John
var x;
document.getElementById("demo").innerHTML += x + ' ';
x = 5;
document.getElementById("demo").innerHTML += x + ' ';
x = "John";
document.getElementById("demo").innerHTML += x + ' ';
<div id="demo"> </div>
Every time you set the innerHTML your overwriting what was there you need to add to it like below.
document.getElementById("demo").innerHTML += x + '<br/>';
Your variable is getting the different values assigned correctly but you are showing all three instances inside the same DOM element. Each time you assign it, the current value overwrites the last value. And it is happening so fast, that you only see the last one ("John").
Why don't you put each one in a different DOM element?
var x;
document.getElementById("demo1").innerHTML = x;
x = 5;
document.getElementById("demo2").innerHTML = x;
x = "John";
document.getElementById("demo3").innerHTML = x;
I wanted to comment on Scath answer but i canĀ“t comment.
Like the others said you are replacing de content, you should use concatenation.
But I would use br tag instead of '\n' to get the expected result.
<script>
var x;
document.getElementById("demo").innerHTML = x+ '<br/>';
x = 5;
document.getElementById("demo").innerHTML += x+ '<br/>';
x = "John";
document.getElementById("demo").innerHTML += x+ '<br/>';
</script>

Operator '+' always concats the value instead of adding

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;
}

What approach should I be using on getting random numbers in javascript?

3h of sleep and I cant figure this out... :S
I had a working something but I am changing the code a lot and removed it now I can not figure it back out.
I really need help...
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a random number between 1 and 100.</p>
<button onclick="myFunction()">myFunction()</button>
<button onclick="myFunction2()">myFunction2()</button>
<p id="demo"></p>
<p id="demo2"></p>
<script>
var number = Math.floor((Math.random() * 100) + 1);
var number2 = 0;
function myFunction() {
number2 = Math.floor((Math.random() * 100) + 1);
var x = document.getElementById("demo")
x.innerHTML = number2;
}
//number2 is still 0.
function myFunction2() {
var x = document.getElementById("demo2")
x.innerHTML = number;
}
//number is stuck at the beginning number
</script>
</body>
</html>
I need to generate new numbers from the myFunction2.
How do I achieve that ?
You are already creating random numbers from using myFunction() and it doesn't seem like a problem. In myFunction2() you don't change or really do anything so how do you expect it to keep creating random numbers? Could you make your question a bit more clear?
Edit: Just place this line inside your myFunction2() instead of where you have kept it and it should work:
var number = Math.floor((Math.random() * 100) + 1);
Enter this before you actually assign anything to var x.
number is defined once at JavaScript at Question. You can use the same approach that you did at myFunction, define number again within myFunction2
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a random number between 1 and 100.</p>
<button onclick="myFunction()">myFunction()</button>
<button onclick="myFunction2()">myFunction2()</button>
<p id="demo"></p>
<p id="demo2"></p>
<script>
var number = 0;
var number2 = 0;
function myFunction() {
number2 = Math.floor((Math.random() * 100) + 1);
var x = document.getElementById("demo")
x.innerHTML = number2;
}
function myFunction2() {
number = Math.floor((Math.random() * 100) + 1)
var x = document.getElementById("demo2")
x.innerHTML = number;
}
</script>
</body>
</html>

Adding two Variables together?

Trying to add two integer variables together, however, I can't seem to figure it out as it just joins them as strings?
var age_child = 10;
var age_gap = 10
alert(age_child+age_gap);
Result: 1010,
Want Result: 20
var age_child = parseInt(10);
var age_gap = parseInt(10);
alert(age_child+age_gap); // should now alert 20
To clarify, in this exact example it is not required to do parseInt. However, I assumed you didn't exactly have 10 in your code either and they're instead variables.
use
parseInt(age_child) + parseInt(age_gap);
let x = 5;
let y = 10;
let sum = x + y;
console.log('The sum of x and y is: ' + sum);

Categories