Display all the values inside an array using a button [duplicate] - javascript

This question already has answers here:
how to append to a object with innerHTML
(7 answers)
Closed 6 years ago.
The function will display all the even numbers between starting number and ending number based on the step value.
For example, if I enter 1, 20, and 3.
I should have 4, 10, and 16 as even number.
I need to push all the numbers inside evenNum array into #result span.
Currently it seems to only display the last even number inside the array.
Further more, if I would like to display all even number in vertical line, how do I do it?
https://codepen.io/anon/pen/wgwaey
<body>
<div class="container">
<h1>Sample</h1>
</div>
<div class="container">
<label>Starting Number: </label>
<input id="startingNum" type="text">
<br>
<label>Ending Number: </label>
<input id="endingNum" type="text">
<br>
<label>Step: </label>
<input id="step" type="text">
<br>
<button onclick="playButton()" id="play">Display Evens</button>
</div>
<div class="container">
<p>Here are the even numbers between <span id="startNum"></span> and <span id="endNum"></span> by <span id="stepNum"></span>'s:</p>
<span id="result"></span>
</div>
</body>
JS:
<script>
function playButton(){
run();
}
function run(){
var x = parseInt(document.getElementById("startingNum").value);
var y = parseInt(document.getElementById("endingNum").value);
var z = parseInt(document.getElementById("step").value);
document.getElementById("startNum").innerHTML = x;
document.getElementById("endNum").innerHTML = y;
document.getElementById("stepNum").innerHTML = z;
var evenNum = [];
while (x < y){
if (x%2 == 0){
evenNum.push(x);
}
x += z;
for (var i = 0; i<evenNum.length; i++){
document.getElementById("result").innerHTML = evenNum[i];
}
}
}
</script>

The problem is here:
for (var i = 0; i<evenNum.length; i++){
document.getElementById("result").innerHTML = evenNum[i];
}
You need to move this out of the while loop and change it to
document.getElementById("result").innerHTML += ' ' + evenNum[i];
// ^ add to existing
Or, more simply, delete the for loop and put this after the while loop:
document.getElementById("result").innerHTML = evenNum.join(' ');

The mistake above is that you're continuously reseting the result's inner HTML, so the last element of even num is the only one displayed. Also, you don't need to be updating result inside of your while loop, you can do it once you're done looking. Try this out!
function playButton(){
run();
}
function run(){
var x = parseInt(document.getElementById("startingNum").value);
var y = parseInt(document.getElementById("endingNum").value);
var z = parseInt(document.getElementById("step").value);
document.getElementById("startNum").innerHTML = x;
document.getElementById("endNum").innerHTML = y;
document.getElementById("stepNum").innerHTML = z;
var evenNum = [];
while (x < y){
if (x%2 == 0){
evenNum.push(x);
}
x += z;
}
for (var i = 0; i<evenNum.length; i++){
document.getElementById("result").innerHTML += "<p>" + evenNum[i] + "</p>";
}
}

Related

Debug this and help to find the solve this [duplicate]

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 2 years ago.
function stringGen(num) {
var result = "";
var alpha =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
var alpha1 = alpha.length;
for (var i = 0; i < num; i++) {
result += alpha.charAt(Math.floor(Math.random() * alpha1));
}
return result;
}
var number = document.getElementById("num");
console.log(stringGen(number));
<html>
<body>
<div>
Enter the length of character:
<input type="text" id="num" />
<button onclick="stringGen(5)">submit</button>
<p id="result"></p>
</div>
<script type="text/javascript" src="app/index.js"></script>
</body>
</html>
Please find the error. I'm not getting the answer to this. I want to display the random text with the length from the value given in the text field in HTML.
I have update your code to fix not showing random text .
At first i get input data by var num = +document.getElementById("num").value; I use + for convert into integer. you code is not showing becouse you do not write any code to show. use document.getElementById("result").innerHTML =result to show in div.
function stringGen(num) {
var result = "";
var alpha =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
var alpha1 = alpha.length;
for (var i = 0; i < num; i++) {
result += alpha.charAt(Math.floor(Math.random() * alpha1));
}
return result;
}
function showResult(){
var num = +document.getElementById("num").value;
document.getElementById("result").innerHTML =stringGen(num);
}
<div>
Enter the length of character:
<input type="text" id="num" />
<button onclick="showResult()">submit</button>
<p id="result"></p>
</div>

Wonder why while not working as expected?

I expected the loop to run 3 times. Can someone tell me what am I doing wrong?
var text = "";
var x = 123;
while (x > 0) {
text += "<br>The number is " + x;
x=x/10;
}
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>
You need to check against 1 instead of zero, because a positive number divided by another positive number is always greater than zero.
var text = "";
var x = 123;
while (x > 1) {
text += "<br>The number is " + x;
x /= 10;
}
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>
I think what you are trying to do is print the number first than remove last digit.If that is the case than, Here x/10 do not return an Integer number that is why the loop is executing more than once. Try the following:
var text = "";
var x = 123;
while (x > 0) {
text += "<br>The number is " + x;
x=Math.floor(x/10);
}
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>

how to use a loop assigning values to inputs depending on another input?

If the value in "master" is even, like 8 I would like that the inputs "bla" would receive 2 each one, if number is odd like 7, the values ​in "bla" would be: 2, 2, 2, 1, 0 and so. I'm trying with this, but the result is undefined
$(document).ready(function(){
var x = $("#master").val();
var z = 0 ;
var i ;
for (i = 0; i <= x ; i++) {
z += x[i];
}
$("#master").change(function(){
$('.bla').val( z ) ;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="master" value="8">
<input class="bla" value="">
<input class="bla" value="">
<input class="bla" value="">
<input class="bla" value="">
To get the results you want you need more logic than you currently have. At least the way your question is worded. First issue is that your initial z value updating only updates once so when you update master the second time, you are not going to get the value you expect.
Next, you are trying, from what I understand, to basically break a number done into 2's a 1 and 0. So to do this you need way more logic to check the values than what you are currently doing. Below, if the value is > 1 we need to append a 2. Otherwise use the value of x. We then decrement x by the value we appended to bla.
$(document).ready(function(){
updateBla();
$("#master").change(function(){
updateBla();
});
function updateBla(){
let x = $('#master').val();
let blahs = document.getElementsByClassName('bla');
for(let i = 0; i < blahs.length; i++){
let val = x > 1 ? 2 : x;
blahs[i].value = val;
x = x - val;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="master" value="8">
<input class="bla" value="">
<input class="bla" value="">
<input class="bla" value="">
<input class="bla" value="">
It's because you're trying to index a integer which, as #Sachintha Sampath has pointed out, doesn't really have an index with a value other than the 0th index. Try this:
$(document).ready(function(){
$("#master").change(function(){
var x = $("#master").val();
var z = [];
for (; x > 0; x -= 2) {
z.push(x >= 2 ? 2 : 1)
}
$('.bla').each(function(index) {
$(this).val(z[index])
})
});
});
NOTE: this code can only display numbers in your format up till 8 in which case there aren't enough inputs to continue displaying the rest of the number.
var z="";
var x=9;
var c=0;
c=Math.floor(x/2);
if(x%2==0){
for (i = 0; i <c ; i++) {
z +=" 2";
}
}else {
for (i = 0; i <c ; i++) {
z +=" 2";
}
z+=" 1 0"
}
console.log(z);

How to generate column numbers and display them on html using JavaScript

I'm a newbie in JavaScript. I want to generate some numbers and display the whole on html element.
Bellow is the code I wrote. I'm only getting a single number generated on html but I'm getting what I want on the console.
var b;
function gen(){
for (var i = 0; i < 10; i++){
b = Math.random().toString();
console.log(b);
document.getElementById('output').innerHTML = b;
};
}
<h1>Generate Phone numbers</h1>
<p>
<input type="button" value="Generate" class="btn" onclick="gen()">
<p>
<span id="output"></span>
Please how do I get what is exactly on the console to html when I click generate button?
Thanks you
You can use insertAdjacentHTML method:
var b;
function gen(){
for (var i = 0; i < 10; i++){
b = Math.random().toString();
document.getElementById('output').insertAdjacentHTML('beforeend', b);
};
}
<h1>Generate Phone numbers</h1>
<p>
<input type="button" value="Generate" class="btn" onclick="gen()">
<p>
<span id="output"></span>
Add a temporary variable to the outside of the loop. Then assign that value to the innerHTML of your span tag.
var phoneNumber = "";
for (var i = 0; i < 10; i++){
b = Math.random().toString();
console.log(b);
phoneNumber += b;
};
document.getElementById("output").value = phoneNumber;

Count the numbers in an array then write them out

It's still old school JS week for newbies at the academy.
I have created an input that makes it possible for a user to put some numbers in a input to write out an array.
Now what I'm trying to do next is writing out a paragraph with a counter for each number, like with how many times the number has been used.
If the array was [0,0,1,1,1,2,2,2,2];
And I want it to write it out something like this:
"How many times does your number appears in your array:"
0: 2
1: 3
2: 4
So far I got it to print out the numbers from the input, but I can't find a way to make it write out like above.
var numbers = [];
function numbarray() {
numbers.push(document.getElementById("box").value);
document.getElementById("text1").innerHTML = "";
document.getElementById("text1").innerHTML += numbers.join(", ");
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="numbarray()" />
<br>
Your array:<span id="text1"></span><br>
After tinkering, failing and googling since yesterday morning I've figure I try out SO again, since I've learned more from this site then I could ever imagine.
Thank you so much in advance
This solution features an object for counting the frequency of the numbers with a focus of occurrence.
function count() {
var numbers = document.getElementById("box").value
.split(',')
.map(Number)
.filter(isFinite),
distribution = numbers.reduce(function (r, a) {
r[a] = (r[a] || 0) + 1;
return r;
}, {});
document.getElementById("text1").innerHTML = numbers.join(", ");
document.getElementById("distribution").innerHTML = Object.keys(distribution)
.sort(function (a, b) {
return distribution[b] - distribution[a];
})
.map(function (k) {
return k + ': ' + distribution[k];
}).join('<br>');
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="count()" /><br>
Your array: <span id="text1"></span><br>
How many times does your number appears in your array:<br>
<div id="distribution"></div>
var numbers = [];
function numbarray() {
numbers = [];
numbers = numbers.concat(document.getElementById("box").value.split(','));
var hash = {};
for(var i=0; i<numbers.length; i++) {
if (typeof hash[numbers[i]] === 'undefined') hash[numbers[i]] = 0;
hash[numbers[i]] ++;
}
document.getElementById("text1").innerHTML = "";
for(var k in hash) {
document.getElementById("text1").innerHTML += k + ': ' + hash[k] + '\n';
}
}
<input type="text" id="box" placeholder="0-9 with comma" />
<input type="button" value="Click" onclick="numbarray()" />
<br>
Your array:<span id="text1"></span><br>
function numbarray() {
var nums = {}; // Use a dictionary for tallying numbers
var numStrings = document.getElementById("box").value.split(","); // Split by commas
// Just tally up each number
for (var i = 0; i < numStrings.length; i++){
var num = numStrings[i];
if (num in nums){
nums[num]++;
}
else {
nums[num] = 1;
}
}
var keys_ = Object.keys(nums); // Get the keys and sort them
keys_.sort();
document.getElementById("text1").innerHTML = "<br>"; // Reset the html
for (var key in keys_){
// Print out each number and its tally
document.getElementById("text1").innerHTML = key + ": " + nums[key] + "<br>";
}
}
Not sure if I totally understand what you are trying to do, but if you want to display the count of each number, you should first get the count of each number, then place them in your DOM, through a function such as:
var numbers = [];
var numbersObject = {};
function numbarray() {
numbers.push(document.getElementById("box").value);
//put numbers in object to get count of each
for(i=0; i<numbers.length; i++){
if(numbersObject[numbers[i]]){
numbersObject[numbers[i]]++
}else{
numbersObject[numbers[i]] = 1
}
}
//prepare HTML
var content = '';
for(var key in numbersObject){
content += key + ':' + numbersObject[key] + '<br>';
}
document.getElementById("text1").innerHTML = content
}

Categories

Resources