Don't show array elements - javascript

I have one array that I want to show in a modal.
The array does have the elements as I have tested this, but it doesn't appear in the modal.
This is the code:
<script>
var selected_items = [];
var i = 0;
function LoadItems() {
for(var j = 0; j < i; j++) {
document.write('<li>' + skins_selected[j] + '</li>');
}
}
function UpdateArray(name)
{
selected_items[i] = name;
i++;
}
</script>
<div class="modal fade" id="modalItems" tabindex="-1" role="dialog" aria-labelledby="labelItems">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="labelItems">¿Confirma que desea depositar los siguientes items?</h4>
</div>
<form class="form-inline" role="form">
<div class="modal-body">
<div class="form-group">
<ul>
<script>
LoadItems();
</script>
</ul>
</div>
</div>
<div class="modal-footer">
<button onclick="mostrar()" class="btn btn-info">Depositar</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
</div>
</form>
</div>
</div>
</div>
P.S: If I put:
<script>
function LoadItems() {
(var j = 0; j < 5; j++) {
document.write(j);
}
}
</script>
it shows me "01234", but when I put the array it doesn't show me anything.

Your current code is looping through the array i times. However, on the previous line i is set to 0. So it's looping 0 times, which is why you get nothing displayed.
I assume you want it to loop through all the items in the array, regardless of how
many elements there are. In that, case you should use the .length property of the skins_selected array:
function LoadItems() {
for(var j = 0; j < skins_selected.length; j++) {
document.write('<li>' + skins_selected[j] + '</li>');
}
}
You can dispense with the i variable entirely.

You are initially setting i, your loop exit condition, to 0. As a result your loop will never run. I.e. you are essentially saying:
for(var j=0; j < 0; j++){
//j is never < 0 so this code never runs
}
Your second example removes this and hardcodes the loop exit condition to the expected value.

<ul>
<script>
var selected_items=[1,2,3,4,5];
var i = 5;
function LoadItems() {
for(var j = 0; j < selected_items.length; j++) {
document.write('<li>' + selected_items[j] + '</li>');
}
}
LoadItems();
</script>
</ul>
your loop is not executing because for(var j = 0; j < i; j++) where j=0 and i=0, so j < i it can be like that.
you should declare i = 5 not i = 0;
Also your array is empty, please put something in your array like
var items_selected = [1,2,3,4,5];

Related

Adding generated values from inputs

I have a site where I can enter the amount of an item, it will then take that input value and return the result on the page. I am then trying to get the results of all the items and return a grand total.
The issue is when I a loop to do this it will only add the first one.
I created a fiddle: https://jsfiddle.net/rc1mgLj5/4/
I am using querySelectorAll and using the length of all the classNames for the result of the first return.
Then looping them after parsing them to a number from text.
But at the moment it is only doing the first calculation. If I delete the for loop the first part works correctly again.
So since its only doing the first calculation for the first item, I get NaN for the second because it does not have a number to parse.
const total = document.querySelectorAll(".tot");
const price = document.querySelectorAll(".cost");
let textval = document.querySelectorAll(".qty-item");
const cal = document.getElementById("calc");
const errorMessage = document.querySelectorAll(".error");
cal.addEventListener("mouseover", function(e) {
console.log(total);
for (var i = 0; i < price.length; i++) {
let xPrice = price[i].innerHTML.split("$");
let parsePrice = parseFloat(xPrice[1]);
if (textval[i].value === "" || isNaN(textval[i].value)) {
setMessage("Please enter a number", "red");
} else {
let x = parseFloat(textval[i].value);
let y = parsePrice;
let z = x * y;
total[i].innerText = z.toFixed(2);
total[i].innerText = z;
for (i = 0; i < total.length; i++) {
let j = parseFloat(total[i].innerHTML);
console.log(j);
}
}
}
});
HTML:
<body>
<div class="main">
<span class="title">A Title</span>
</div>
<div class="content">
<div class="item">
<span>Item 1</span>
</div>
<div>
<span class="cost">$100.00</span>
</div>
<div id="qty">
<label>QTY:</label><input placeholder="0" class="qty-item">
<p class="error"></p>
</div>
<div class="tot">
<span><label>TOTAL</label> $0.0</span>
</div>
</div>
<br><br>
<div class="main">
<span class="title">A Title</span>
</div>
<div class="content">
<div class="item">
<span>Item 2</span>
</div>
<div>
<span class="cost">$50.00</span>
</div>
<div class="qty">
<label>QTY:</label><input placeholder="0" class="qty-item">
<p class="error"></p>
</div>
<div class="tot">
<span><label>TOTAL</label> $0.0</span>
</div>
</div>
<div class="calc-button">
<button id="calc">Calculate Prices</button>
</div>
</body>
You are nesting two fors using the same i variable as index:
cal.addEventListener('mouseover', function(e) {
console.log('total', total);
for (var i = 0; i < price.length; i++) {
//...
for (i = 0; i < total.length; i++) { // <== uses "i" again
let j = parseFloat(total[ii].innerHTML);
console.log(j);
}
}
}
});
Just replace that second for's variable with another name. Example:
for (let k = 0; k < total.length; k++) {
let j = parseFloat(total[k].innerHTML);
console.log(j);
}
Demo: https://jsfiddle.net/acdcjunior/gpLvszx3/
It seems you are using the same variable "i" for both loops and i is being reset in the second loop to 3 and hence the main loop runs only once. So i removed the following code and calculated the total outside main loop. seems to be working fine now. https://jsfiddle.net/uxr7ac9k/7/
total[i].innerText = z;
for (i=0;i < total.length; i++){
let j = parseFloat(total[i].innerHTML);
console.log(j);
}

Pascal Triangle array not showing in HTML? How do i solve it?

<head>
<title> Pascal’s Triangle </title>
</head>
<body>
<header>
<div id="strong"> Pascal’s Triangle </div>
</header>
<div class="container">
<div>
<span id="enter"> Please enter any number: </span><input id="number" /> <br id="screen"/>
<button id="button" onclick="createPascalTriangle()"> Check »</button>
</div> <br/>
</div>
<div id="show"> </div>
<footer>
<div> ©Technical Challenge </div>
<footer>
<script>
function createPascalTriangle () {
var pascalTriangle = [];
var numRows = document.getElementById("number").value;
for (var i = 0; i < numRows; i++) {
pascalTriangle[i] = new Array(i+1);
for (var j = 0; j < i+1; j++) {
if (j === 0 || j === i) {
pascalTriangle[i][j] = 1;
} else {
pascalTriangle[i][j] = pascalTriangle[i-1][j-1] + pascalTriangle[i-1][j];
}
}
}
return pascalTriangle;
pascal = JSON.Stringify(pascalTriangle);
document.getElementById("show").innerHTML = pascal;
}
</script>
</body>
Pascal Triangle array not displaying in expected 'div'
How do i display these array of Pascal Triangle in HTML?
Here is my code. The 'div 'is not displaying anything
i tried the innerHTML property. the pascalTriangle output is an Array. But i'm unable to display the output in html
The problem might be:
its JSON.stringify (capitalization)
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
You are doing actions after your function returns a value. The function stops being executed as soon as the return statement is reached. You should write at the end of the function:
pascal = JSON.stringify(pascalTriangle);
document.getElementById("show").innerHTML = pascal;
return pascalTriangle;

append images from DB into a div in jQuery

I am trying to show images of a particular holiday package from my DB into a slider using jQuery append. My slider is inside a modal and this modal is shown from javascript function. But I am only getting one image into the slide show. I am using while loop to iterate the image array and it is added to the div using innerhtml. I don't know where I am going. Can anyone please help me?
Here is my code:
js
function showDetailsModal(id) {
$.post('uae-holidaydetails.php',{uaeid:""+id+""},function(data){
data = jQuery.parseJSON(data);
var datadet= data[0];
if(data[1]) {
var dataimg= data[1];
var imgarray=[];
for (index = 0; index < dataimg.length; index++) {
imgarray.push(dataimg[index].image);
}
var i=0;
while(imgarray[i]){
document.getElementById("detail-banner").innerHTML='<div class="item"><img src="../sysimages/origimages/'+imgarray[i]+'" alt=""></div>'; //here I am creating the div for slider
i++;
}
}
document.getElementById("uaetitle").innerHTML= datadet.title;
document.getElementById("subtitle").innerHTML= datadet.subtitle;
$('#holiday-details').modal('show'); //modal is shown
});
}
php
<?php
include_once("index.class.php");
$objScr = new INDEX();
if(isset($_POST['uaeid'])) {
$uaeid=$_POST['uaeid'];
$rslthlydata = $objScr->getUaedata($uaeid); //get holiday details
$rowuaedetails = $rslthlydata->fetchAssoc();
$resultimages= $objScr->getUaeholyImages($uaeid); //get images
while($resultimg=$resultimages->fetchAssoc()) {
$dataimg[]=$resultimg;
}
echo json_encode(array($rowuaedetails,$dataimg)) ;
}
html
<div class="modal fade" id="holiday-details" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">CLOSE <img src="images/close-btn.png" alt=""></button>
<div class="modal-body">
<!--<section class="banner detailed"></section> -->
<div class="owl-carousel owl-theme" id="detail-banner" >
//this is the slider
</div>
<div class="details">
<h3 class="top-line" id="uaetitle"></h3>
<h4 id="subtitle"></h4>
</div>
</div>
</div>
</div>
</div>
Edit 1
I tried append also. When I append I am getting the whole images but it's not shown as slider
$('#detail-banner').append('<div class="item"><img src="../sysimages/origimages/'+imgarray[i]+'" alt=""></div>');
Try this, no need to mix pure JS and jQuery. Pick one and stick to it ;)
jQuery(document).ready(function($){
function showDetailsModal(id) {
$.post('uae-holidaydetails.php', {uaeid: id }, function(data) {
var data = JSON.parse(data);
var dataDet = data[0];
if(data[1]) {
var dataImg = data[1];
var imgArray = [];
for (var index = 0; index < dataImg.length; index++) {
imgArray.push(dataImg[index].image);
}
var items = "";
for (var j = 0; j < imgArray.length; i++) {
items += '<div class="item"><img src="../sysimages/origimages/'+imgArray[j]+'" alt=""></div>';
}
$('#detail-banner').append(items);
}
$('#uaetitle').append(dataDet.title);
$('#subtitle').append(dataDet.subtitle);
$('#holiday-details').modal('show'); //modal is shown
});
}
});
You have to concat your image array data using + to create all images.You have to use innerHTML += to avoid replacing the content of a node Like following.
function showDetailsModal(id) {
$.post('uae-holidaydetails.php',{uaeid:""+id+""},function(data){
data = jQuery.parseJSON(data);
var datadet= data[0];
if(data[1]) {
var dataimg= data[1];
var imgarray=[];
for (index = 0; index < dataimg.length; index++) {
imgarray.push(dataimg[index].image);
}
var i=0;
var imageContent = "";
for (var j = 0; j < imgArray.length; i++) {
imageContent +='<div class="item"><img src="../sysimages/origimages/'+imgarray[j]+'" alt=""></div>'; //here I am creating the div for slider
}
}
document.getElementById("detail-banner").innerHTML = imageContent;
document.getElementById("uaetitle").innerHTML= datadet.title;
document.getElementById("subtitle").innerHTML= datadet.subtitle;
$('#holiday-details').modal('show'); //modal is shown
});
}
For example let's consider the following scenario:
var array = [1,2,3,4];
for(var i=1;i<=array.length;i++){
document.getElementById("test1").innerHTML = i+" ";
}
for(var j=1;j<=array.length;j++){
document.getElementById("test2").innerHTML += j+" ";
}
<div id="test1"></div>
<div id="test2"></div>

Add dynamic buttons to the beginning

I add couple of buttons in to a DIV.
var newVr = "";
for(i=0; i<5; i++){
newVr += '<button type="button" class="abc">New</button>';
}
document.getElementById('extraDIV')innerHTML += newVr;
Instead of adding the buttons to the end of the buttons, how do I add the new buttons at the beginning?
Expected output after new buttons are added e.g.
[new] [new] [old] [old] [old] [old] [old] [old]
You can use prepend()
for(i=0; i<5; i++){
$('#extreDIV').prepend('<button type="button" class="abc">New</button>');
}
for (i = 0; i < 5; i++) {
$('#extreDIV').prepend('<button type="button" class="abc">New</button>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="extreDIV">
<button type="button" class="abc">Old</button>
<button type="button" class="abc">Old</button>
<button type="button" class="abc">Old</button>
</div>
Since you have tagged the question with jquery
for (i = 0; i < 5; i++) {
$("#extraDIV").prepend('<button type="button" class="abc">New</button>');
}
Try to use prepend() like,
var newVr = "";
for(i=0; i<5; i++){
newVr += '<button type="button" class="abc">New</button>';
}
$('#extreDIV').prepend(newVr);
var newVr = "";
for(i=0; i<5; i++){
newVr += '<button type="button" class="abc">New '+(i+1)+'</button>';
}
$('#extreDIV').prepend(newVr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="extreDIV"></div>
you can use Node.insertBefore()
// Create a new, plain <span> element
var sp1 = document.createElement("span");
sp1.innerHTML = 'I am new span ';
// Get a reference to the element, before we want to insert the element
var sp2 = document.getElementById("childElement");
// Get a reference to the parent element
var parentDiv = sp2.parentNode;
// Insert the new element into the DOM before sp2
parentDiv.insertBefore(sp1, sp2);
<div id="parentElement">
<span id="childElement">foo bar</span>
</div>
Find the example in jsFiddld https://jsfiddle.net/92j135v9/1/prepend.
Also check the jQuery documentation for prepand http://api.jquery.com/prepend/ for more examples.

onBlur in innerHtml blocks the function

I have 2 functions, one that is creating dynamicly a table with input fields, which dimensions are based on a variable k, inserted by the user, and another one that reads the values inserted again by the user in every field of the table and inserts them in a 2 dimensional array that I can call later.
The problem is that the create table function does not work with onBlur inserted in it's code.
The code is as follows:
<head>
<script>
var k;
function genArray () {
var A = [];
for (var i = 0; i < k; i++) {
A[i] = [];
for (var j = 0; j < k; j++) {
var id = "A" + (i + 1) + (j + 1);
A[i][j] = parseFloat(document.getElementById(id).value);
if (isNaN (A[i][j])) {
alert ('Valoarea 'A[i][j]' nu este un numar. Reintroduceti valoarea');
}
}
}
}
function readGrad() {
k = parseInt(document.getElementById("grad").value);
if (isNaN(k)) {
alert('Gradul introdus nu este intreg, reintroduceti gradul matricii');
}
if (k == 0) {
alert ('Determinantul trebuie sa fie mai mare ca 1');
}
if (k == 1) {
alert ('Determinantul trebuie sa fie mai mare ca 1');
}
return k;
}
function genTable(i,j) {
//var i,j = parseInt(document.getElementById("grad").value);
var myTable = '<TABLE BORDER="1" BORDERCOLOR="BLACK">\n <TBODY>\n';
for (i = 0; i < 1; i++) {
myTable += ' <TR>\n';
for (j = 0; j < k+1; j++) {
myTable += ' <TD>'+j+'</TD>\n';
}
myTable += ' </TR>\n';
}
for (i = 1; i < k+1; i++) {
myTable += ' <TR>\n';
for (j = 0; j < 1; j++) {
myTable += ' <TD>'+i+'</TD>\n';
}
for (j = 1; j < k+1; j++) {
myTable += ' <TD><input class="element" id="A' + i + j + '" onblur="genArray()"></TD>\n';
}
myTable += ' </TR>\n';
}
myTable += ' </TBODY>\n</TABLE>\n';
document.getElementById('container').innerHTML = myTable;
}
</script>
</head>
<body style="background-color: #777; color: ddd;">
<div style="margin: 20px;">
<h1>Program de calculare determinant matrice de orice grad.</h1>
</div>
<div>
Introduceti gradul matricei
<input id="grad" type="text" value="" style="width: 50px;" onChange="readGrad()">
<input style="margin-top: 20px;" type="button" name="Calculate determinant" value="Generati tabel" onClick="genTable()">
</div>
<form name="Det Matrice">
<div style="margin-top: 100px; float: left; width: 100%;">
Introduceti valorile:
<table style="text-align: center;">
<div id="container"></div>
</table>
<br>
</div>
</body>
After correct the syntax error of the alert, genTable() works. But you have logic problem in your code. You add onblur event handler to every text field in the generated table cell. So every cell input will trigger a call to the onblur event handler which will iterate the whole table. I don't think this is what you want. Besides, during the iteration, your parseFloat function will fail on all the empty cells. You should only trigger one call to genArray() perhaps by using a button.
Try onblur="genArray()" instead of onBlur="genArray()"
Notice that it is all in lower case letters!
Your code works fine. Just correct the syntactical error in line 15 like described by jbabey in the comments.

Categories

Resources