Images in dynamic divs not displayed - javascript

I am looping through images and create dynamic divs. But the images are not displayed, though console.log() shows that parameters of ready() function in the loop are valid. It shows myDiv1 and address of the first image in the array and myDiv2 and address of the second image. What's wrong with the code?
Here's my code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="view_topic.css">
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<div id="outerdiv"></div>
<script>
$(document).ready(function() {
$('#outerdiv').append(
$('<div>').prop({
id: 'myDiv1',
//innerHTML: 'Hi there!',
className: 'img-wrapper'
})
);
});
$(document).ready(function() {
$('#outerdiv').append(
$('<div>').prop({
id: 'myDiv2',
//innerHTML: 'Hi there!',
className: 'img-wrapper'
})
);
});
$(this).css('height',"100px");
var get_a_image = ["http://iancaple.ru/upload/images/20200804_225812.jpg", "http://iancaple.ru/upload/images/8871677_tsumpy_laba_3.docx"];
var counter = 1;
var ready_cnt = 0;
for (var i = 0; i < 2; i++) {
$(document).ready(function() {
$('#myDiv' + ready_cnt + 1).append($('<img id="theImg2">').attr({
'src': get_a_image[ready_cnt] , //'https://' + imgUrl ,
'alt': 'test image ' + ready_cnt + 1
})
).scrollTop(9999)
console.log("get_a_image[" + ready_cnt + "]=" + get_a_image[ready_cnt]);
console.log('#myDiv' + (ready_cnt + 1));
ready_cnt++;
});
}
</script>
</body>
<html>

Use parentheses to get the increased value of ready_cnt. If not, it will be regarded to select an ID of myDiv01
$('#myDiv' + (ready_cnt + 1)).append(...)

Related

The H1 tag wont load on my page only the javascript part, why is that?

When I load this page to the browser the Javascript shows up but the HTML (H1 tag) doesn't. I haven't been able to figure out why I cant get HTML to show up on the page. Im new to both Javascript and HTML...clearly.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script src="data_generator.js"></script>
</head>
<body>
<h1>hello</h1>
<script>
$(document).ready(function(){
var $body = $('body');
$body.html('');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message);
$tweet.appendTo($body);
index -= 1;
}
});
</script>
You are removing the <h1> tag when you clear the inner HTML of the body tag by calling $('body').html(''). Why don't you work in a different container element that you can clear:
<body>
<h1>Hello, world!</h1>
<div id="root"></div>
<script>
$(document).ready(function(){
var $root = $('#root');
// $root.html(''); // Already empty. Don't need to clear it.
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message);
$tweet.appendTo($root);
index -= 1;
}
});
</script>
</body>
As #charlietfl said, $body.html(''); clears all previous html content of the body tag. More simply it just replaces the contents with what is inside the quotes, or in this case nothing.
Here is documentation on the subject:
JQuery html() Documentation
EDIT:
Inspired by Sean's answer,
If you want to use the body container directly you can do so like this:
<body>
<h1>Hello, world!</h1>
<script>
$(document).ready(function(){
var $body = $('body');
// $body.html(''); // This clears it and since you don't want to, you shouldn't run this command.
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message);
$tweet.appendTo($body);
index -= 1;
}
});
</script>
</body>

How To Convert CSV file to HTML table

i have csv file with the content :
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
I create Javascript/HTML code to pick up that file and display the content
<html>
<head>
<title>show csv</title>
</head>
<body>
<input type="file" id="fileinput" multiple />
<div id="result"></div>
<script type="text/javascript">
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
var res = document.getElementById("result");
res.innerHTML = "Got the file<br>"
+"name: " + f.name + "<br>"
+"type: " + f.type + "<br>"
+"size: " + f.size + " bytes</br>"
+ "starts with: " + contents;
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change',readMultipleFiles, false);
</script>
</body>
</html>
and the output is like :
output
question : How can i convert the content or the data to array and showing as html table ?
thanks for any help.
You can convert csv data into array and then into html table. I have added \n into your new line. Please add the \n to your code when there is a new line.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
</head>
<body>
<div id='container'></div>
<script type="text/javascript"charset="utf-8">
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice(0,-1).split(",").join("</td><td>")
+ "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var div = document.getElementById('container');
div.innerHTML = output;
</script>
</body>
</html>
I found Kapila Perera's answer to be very useful. However, the last element of each row was being cropped due to the slice(0,-1) use. Building on Perera's answer, in the example below I've used slice() instead.
I've also separated out the first row lines[0] as a header row and loop from 1 instead (which won't always be the case that csv contains headers but is explicitly called out in the example).
Finally, I've added the tbody tags when the output gets wrapped but this probably isn't required.
<script type="text/javascript"charset="utf-8">
var div = document.getElementById('container');
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"), output = [], i;
/* HEADERS */
output.push("<tr><th>"
+ lines[0].slice().split(",").join("</th><th>")
+ "</th></tr>");
for (i = 1; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice().split(",").join("</td><td>")
+ "</td></tr>");
output = "<table><tbody>"
+ output.join("") + "</tbody></table>";
div.innerHTML = output;
</script>

Get Value in HTML Table using Button

I have a simple table that is populated using an array:
for (var i = 0; i < results.length; i++) {
var object = results[i];
(function($) {
$('#results-table').append('<tbody><tr><td>' + object.get('Name') + '</td><td>' + object.get('Description') + '</td><td><button class="button" onclick="goToClass()">View Class</></tr></tbody>');
})(jQuery);
Ideally I would like the goToClass() function to give me the object.ID for that individual row that was selected.
So for example, if I select the button on the first row in the table it would give me the object.ID for that class.
How would I do this?
Try this:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<table id="results-table">
</table>
</body>
<script>
results = [
{Name:1,Description:"one",ID:1111},
{Name:2,Description:"two",ID:2222},
{Name:3,Description:"Three",ID:3333}
]
for (var i = 0; i < results.length; i++) {
var object = results[i];
(function($) {
$('#results-table').append('<tbody><tr><td>' + object['Name'] + '</td><td>' + object['Description'] + '</td><td><button class="button" onclick="goToClass('+object['ID'].toString()+')">View Class</></tr></tbody>');
})(jQuery);
}
function goToClass(id) {
console.log(id)
}
</script>
</html>
When I click the buttons, the console gives me the correct id in each case.

JQuery Programmatically adding articles

I am trying to programmatically add articles to my website and then add a random word to each article using Jquery. I am able to make all the articles but I am not able to add text to the articles. Here is my code:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js" type="text/javascript"></script>
<script src="Script/jquery.lorem.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function ()
{
var colors = ["#CCCCCC", "#333333", "#990099"];
var rand = Math.floor(Math.random() * colors.length);
$(function () {
for (var i = 0; i < Math.floor((Math.random() * 64) + 34) ; i++) {
$("#Inferface").append("<article class='box' style='background-color:" + colors[rand] + "'><span>" + i + "</span>");
}
});
// This line below should be adding the random word to each of the articles
$('.box').lorem({ type: 'words', amount: '1', ptags: false });
});
</script>
</head>
<body id="Inferface">
</body>
</html>
Strange, It seems to me that the code is working with very few adjustments
$(function ()
{
var colors = ["#CCCCCC", "#333333", "#990099"];
var rand = Math.floor(Math.random() * colors.length);
for (var i = 0; i < Math.floor((Math.random() * 64) + 34) ; i++)
{
$("#Interface").append("<article class='box' style='background-color:" + colors[rand] + "'><span>" + i + "</span>");
}
// This line below should be adding the random word to each of the articles
$('.box').lorem({ type: 'words', amount: '1', ptags: false});
});
.. you can check it out here :
Working Example

Appending to a tag

I want to append data I fetched from server to a div tag, but I can't get it to work. That's HTML with a div tag to which I'd like to append data from the JS code.
HTML:
<body onload="initialize()">
<div id="text"></div>
</body>
And here is JavaScript code. I would like to replace document.write with a function that will append data to a div tag.
JS:
function initialize() {
$.getJSON('http://www.wawhost.com/izdelava-mobilne-aplikacije-2-del/fetch.php?callback=?', function (data) {
for (var i = 0; i < data.length; i++) {
document.write('<img src="' + data[i].image + '" />' + data[i].title + data[i].description + '<br>');
}
});
}
Fiddle: http://jsfiddle.net/GDxtf/
I just started learning JavaScript. Help will be greatly appreciated :)
Paste this code in the bottom of your HTML document, right before </body>:
<script>
// If you're not using an HTML5 doctype, use <script type="text/javascript> instead of just <script>
$(function () {
$targetDiv = $("#text");
$.getJSON('http://www.wawhost.com/izdelava-mobilne-aplikacije-2-del/fetch.php?callback=?', function (data) {
for (var i = 0; i < data.length; i++) {
var $div = $("<div />");
var $img = $("<img />");
$img.attr("src", data[i].image);
$img.appendTo($div);
var $title = $("<h2>" + data[i].title + "</h2>");
$title.appendTo($div);
var $description = $("<p>" + data[i].description + "</p>");
$description.appendTo($div);
$div.appendTo($targetDiv);
}
});
});
</script>
Did this solve your problem?

Categories