whats wrong with this code? when i click on button it shows undefined before first array value:
function loadDoc() {
var x;
var edare = JSON.parse('{"names":["ali", "mansour", "taghi"]}');
for (var i in edare.names) {
x += edare.names[i] + "<br>";
document.getElementById("demo").innerHTML = x;
}
}
<input type="button" onclick="loadDoc();" value="test">
<p id="demo"></p>
Because your x variable's initial value is undefined. So when you try to concatenate with another string it does undefined + string.
To fix this, you should give an initialize value to your variable:
var x = "";
Also, you should use for loops instead of for...in for arrays. Take a look at this for more information.
And finally, should also move your .innerHTML = x; outside of the loop to prevent updating the DOM on every iteration.
var x = "";
var edare = JSON.parse('{"names":["ali", "mansour", "taghi"]}');
for (var i=0; i<edare.names.length; i++) {
x += edare.names[i] + "<br>";
}
document.getElementById("demo").innerHTML = x;
Use .reduce() to construct a single string from the array of strings.
That way you only need to set the .innerHTML once.
function loadDoc() {
const edare = JSON.parse('{"names":["ali", "mansour", "taghi"]}');
document.getElementById("demo").innerHTML = edare.names.reduce((s, itm) =>
s + itm + "<br>"
, "")
}
<input type="button" onclick="loadDoc();" value="test">
<p id="demo"></p>
Or just .join() the list.
function loadDoc() {
const edare = JSON.parse('{"names":["ali", "mansour", "taghi"]}');
document.getElementById("demo").innerHTML = edare.names.join("<br>");
}
<input type="button" onclick="loadDoc();" value="test">
<p id="demo"></p>
Only difference here is that there's no trailing <br> at the end, but you can easily add that in if you really want it.
but it works with this:
function loadDoc() {
var x="";
var edare = JSON.parse ('{"names":["ali", "mansour", "taghi"]}');
for (var i in edare.names) {
x += edare.names[i] + "<br>";
document.getElementById("demo").innerHTML = x;
}
}
Iterate your array properly:
var i, nameConcat = "";
for(i=0; i < edare.names.length; i++){
nameConcat += edare.names[i] + "<br>";
}
document.getElementById("demo").innerHTML = nameConcat;
Or:
var concatNames = "";
edare.names.forEach(function(name){
nameConcat += name + "<br>";
});
document.getElementById("demo").innerHTML = nameConcat;
Related
Need help with assignment. I need to create a button that uses a for loop to multiply each number in the array by the number after it into a second array and display the result. Lastly create another button that uses a while loop that divides each number in the array by the number after it into a third array and once more display the result. I have created a way to input numbers into an array "numbers" and display the array but do not know how to use for loops to display the quotient nor the product please help :(
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="number" id="num" min="0" max="100">
<button onclick="myFunction()">Try it</button>
<button onclick="SortFunction()">Sort it</button>
<button onclick="AddFunction()">Add it</button>
<p id="demo"></p>
<script>
var myarray =[] ;
var text ;
function myFunction()
{
var fLen ;
var x = document.getElementById("num").value;
var i ;
myarray.push(Number(x));
fLen = myarray.length ;
text = "<ul>";
for (i = 0; i < fLen; i++)
{
text += "<li>" + myarray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
}
function SortFunction()
{
myarray.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = myarray;
}
function AddFunction()
{
var sum = 0 ;
var fLen ;
var i ;
fLen = myarray.length ;
for (i = 0; i < fLen; i++)
{
sum = sum + Number(myarray[i]);
}
document.getElementById("demo").innerHTML = sum;
}
</script>
Well, simply you could add these buttons and try to create some special logic for each button inside relevant function, for example MultiplyNumbers() and DivideNumbers():
<button onclick="MultiplyNumbers()">Multiply pairs</button>
<button onclick="DivideNumbers()">Divide pairs</button>
In both functions firstly you should check if the main array has paired values via dividing length with 2 -> length % 2 == 0, then check if they're valid numbers with isNaN() function, if some value in pair is not valid you can define the result of this math equal 0 or what you want. Dividing function request also checking the second value in each pair with 0, cause you can't divide a number with zero(or you can).
So, the first function works via for loop, the second one via while loop.
The snippet below shows you this two functions, they're work correctly with this simple rules. If I've missed something you can tell me.
var myarray =[] ;
var text ;
function myFunction()
{
var fLen ;
var x = document.getElementById("num").value;
var i ;
myarray.push(Number(x));
fLen = myarray.length ;
text = "<ul>";
for (i = 0; i < fLen; i++)
{
text += "<li>" + myarray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
}
function SortFunction()
{
myarray.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = myarray;
}
function AddFunction()
{
var sum = 0 ;
var fLen ;
var i ;
fLen = myarray.length ;
for (i = 0; i < fLen; i++)
{
sum = sum + Number(myarray[i]);
}
document.getElementById("demo").innerHTML = sum;
}
function MultiplyNumbers() {
let multNumbers = [];
if (myarray.length % 2 == 0){
let actions = myarray.length / 2;
for(let i = 0; i < actions; i++){
var tmult = (isNaN(myarray[i*2]) || isNaN(myarray[i*2+1])) ?
0 :
Number(myarray[i*2]) * Number(myarray[i*2+1]);
multNumbers.push(tmult);
}
document.getElementById("demo").innerHTML = multNumbers;
}
}
function DivideNumbers() {
let divNumbers = [];
if (myarray.length % 2 == 0){
let actions = myarray.length / 2;
let i = 0;
while(i<actions){
var tdiv = (isNaN(myarray[i*2]) || isNaN(myarray[i*2+1]) || Number(myarray[i*2+1]) == 0) ?
0 :
Number(myarray[i*2]) / Number(myarray[i*2+1]);
divNumbers.push(tdiv);
i++;
}
document.getElementById("demo").innerHTML = divNumbers;
}
}
<input type="number" id="num" min="0" max="100">
<button onclick="myFunction()">Try it</button>
<button onclick="SortFunction()">Sort it</button>
<button onclick="AddFunction()">Add it</button>
<button onclick="MultiplyNumbers()">Multiply pairs</button>
<button onclick="DivideNumbers()">Divide pairs</button>
<p id="demo"></p>
var myarray =[] ;
var text ;
function myFunction()
{
var fLen ;
var x = document.getElementById("num").value;
var i ;
myarray.push(Number(x));
fLen = myarray.length ;
text = "<ul>";
for (i = 0; i < fLen; i++)
{
text += "<li>" + myarray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
}
function SortFunction()
{
myarray.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = myarray;
}
function AddFunction()
{
var sum = 0 ;
var fLen ;
var i ;
fLen = myarray.length ;
for (i = 0; i < fLen; i++)
{
sum = sum + Number(myarray[i]);
}
document.getElementById("demo").innerHTML = sum;
}
// updated code
var secondArray=[];
function multiplyFunction(){
var temp = document.getElementById("num").value;
for(i=0;i<myarray.length;i++){
secondArray.push(Number(temp) * myarray[i]);
}
// show new array ..
text = "<ul>";
for (i = 0; i < myarray.length; i++){
text += "<li>" + secondArray[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
//
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="number" id="num" min="0" max="100">
<button onclick="myFunction()">Try it</button>
<button onclick="SortFunction()">Sort it</button>
<button onclick="AddFunction()">Add it</button>
<button onclick="multiplyFunction()">Multiply</button>
<button onclick="divideFunction()">Divide</button>
<p id="demo"></p>
</body>
</html>
<script>
var y="<br>"
function repeater(num){
for (var i=0;i<num;i++)
{document.write(y) }
}
document.write(repeater(4))
</script>
My goal is to make the tag appear
4 times, not the actual breaks. The result shows undefined.
Since the question is asking for Javascript solution not JQuery (since no jQuery tags), I'll add the answer using Javascript.
<script>
var y = "<br>"
function repeater(num) {
for (var i=0; i < num; i++) {
document.body.innerText += y;
}
}
repeater(4);
</script>
or maybe you need to set a text into the spesific element (<div id="app"><div>)? no problem, we can improve the code a little bit.
<script>
var y = "<br>"
function repeater(el, num) {
for (var i=0; i < num; i++) {
el.innerText += y;
}
}
var el = document.getElementById('app');
repeater(el, 4);
</script>
<script>
var res = "";
var y="<br>";
function repeater(num){
for (var i=0;i<num;i++) {
res = res + y;
}
$('#customDiv').text(res);
}
(repeater(4))
You can put a custom <div id="customDiv"></div> inside your html file.
function myFunction() {
var text = "";
var i;
for (i = 0; i <= 10; i++) {
text += + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
I want to add present i value into previous loop output value. This maybe a simple question. I have searched in google and stackoverflow. But, didn't get the desired result.
In above screenshot,
0 is the previous loop value + 1 is present i returns => 1
1 is the previous loop value + 2 is present i returns => 3
3 is the previous loop value + 3 is present i returns => 6
6 is the previous loop value + 4 is present i returns => 10
You need another persistent variable that keeps track of the last total that was concatenated with text:
function myFunction() {
var text = "";
var i;
var lastTotal = 0;
for (i = 0; i <= 10; i++) {
var newTotal = lastTotal + i;
text += + newTotal + "<br>";
lastTotal = newTotal;
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
(technically, you don't need the newTotal variable, but it makes the code's intent more clear)
You could also do this a bit more elegantly with reduce:
function myFunction() {
let text = '';
Array.from({ length: 11 }, (_, i) => i)
.reduce((lastTotal, i) => {
const newTotal = lastTotal + i;
text += newTotal + '<br>';
return newTotal;
}, 0);
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
You just need a second variable to hold the last value:
function myFunction() {
var text = "";
var sum = 0;
for (var i = 0; i <= 10; i++) {
sum += i;
text += sum + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
Keep a count of the last number:
function myFunction() {
var text = "";
var i;
var count = 0;
for (i = 0; i <= 10; i++) {
count += i;
text += count + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
You can use the function reduce to fill the operations and then use the function forEach to build the desired output.
function myFunction() {
var html = "";
Array.from({length: 10}, (_, i) => i + 1).reduce((a, c, i) => {
a[i] = (a[i - 1] || 0) + c;
return a;
}, []).forEach((n, i, arr) =>
(html += (arr[i - 1] || 0) + " + " + (i + 1) + " = " + n + "<br>"));
document.getElementById("demo").innerHTML = html;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
I think I'd just use an array so that you both have the previous sum, and can also use it with .join() for setting the HTML.
function myFunction() {
for (var i = 0, a = []; i <= 10; i++) {
a[i] = i + (a[i-1] || 0);
}
document.getElementById("demo").innerHTML = a.join("<br>");
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
how to display element one by one on click using only Javascript, in my example when I click all elements show at once, but i need only one click - one element. I appreciate if you show the simplest way to do if in order to i can understand how it works
$(function() {
var cars = ["audi", "bmw", "volvo"];
var x = "";
var i;
for (i = 0; i <cars.length; i++) {
x += cars[i] + "<br>";
}
document.getElementById("btn").onclick = function() {
document.getElementById("text").innerHTML = x;
}
});
You may update your code as follows. At the very beginnig, your are initializing x with empty string. Then for each click on button, append an element from array with new line tag.
var cars = ["audi", "bmw", "volvo"];
var x = "";
var i = 0;
document.getElementById("btn").onclick = function() {
if( i < cars.length) {
x += cars[i++] + "<br>";
}
document.getElementById("text").innerHTML = x;
}
<p id="text"></p>
<button id="btn">Result</button>
<html>
<script>
var cars = ["audi", "bmw", "volvo"];
var x = "";
var count = 0;
function appendArray(){
if(count<cars.length){
x += cars[count]+ "<br>";
document.getElementById("appendText").innerHTML = x;
count++;
}else{
count = 0;
document.getElementById("appendText").innerHTML = "";
}
}
</script>
<p id="appendText"></p>
<button onclick="appendArray()">Submit</button>
</html>
Here is one solution in vanilla javascript:
var button = document.getElementsByTagName('button')[0];
var i = 0;
function addCar(i) {
var cars = ['audi', 'bmw', 'volvo'];
var paragraph = document.getElementsByTagName('p')[0];
if (i < cars.length) {
var newLine = document.createElement('br');
var newCar = document.createTextNode(cars[i]);
paragraph.appendChild(newLine);
paragraph.appendChild(newCar);
}
}
button.addEventListener('click',function(){addCar(i); i++;},false);
<p></p>
<button>Click for a New Car</button>
i need some code corrected. So here is the JS:
var $ = function (id) {
return document.getElementById(id);
}
var myTransaction = new Array[];
function processInfo() {
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = myTransaction;
for (var theTotal in myTransaction) {
myTransaction += addTogether[theTotal] + "<br>";
}
}
window.onload = function () {
$("addbutton").onclick = processInfo;
}
and HTML
<section>
<p>Item:
<input type="text" id="item" size="30">
<p>Amount:
<input type="text" id="amount" size="30">
<p><span id="message">*</span>
<p>
<input type="button" id="addbutton" value="Add Item" onClick="processInfo();">
</section>
What i need to do is get the values of the text boxes, and add them together into one variable then have it stored into the array. Then use a for-in loop to concatenate every element in the Array into a one String variable. However, must also stick a tag at the end every value in the String, last thing is place this String in a paragraph at the end of the page.
FIDDLE
If I understand you then look at my edition to your code:
If you not understand something with the code so ask me.
At first you forget to close with ; the function $.
then you create array with bad syntax.
third you call addTogether array that doesn't exist.
this is fixed code that i belive working like you asked.
var $ = function(id) {
return document.getElementById(id);
};
var myTransaction = [];
function processInfo ()
{
var myItem = $('item').value;
var myAmount = parseFloat($('amount').value);
var myTotal = myItem + ":" + myAmount;
var myParagraph = $('message');
myParagraph.innerHTML = "";
myTransaction.push(myTotal);
for (var theTotal in myTransaction)
{
myParagraph.innerHTML += myTransaction[theTotal] + "<br>";
}
};
(function () {
$("addbutton").onclick = processInfo;
})();
Edit
Mohamed-Ted suggest:
instead of:
for (var theTotal in myTransaction)
{
myParagraph.innerHTML += myTransaction[theTotal] + "<br>";
}
you can do this:
myParagraph.innerHTML += myTransaction.join("<br>");
see example on:
jsFiddle