Javascript Filereader sort by name - javascript

i'm trying to list my image preuploader sort by name but got some issues.i have dozen image with name img001 - img100 but when i input that the result show the files sort by image size. here is my code
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<title>generate nama ikan</title>
</head>
<body>
<div class="flex-center position-ref full-height">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Nama Ikan</h1>
<input id="ingambar" type="file" multiple />
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="content">
<br />
<table class="table">
<thead>
<th>gambar</th><th>nama</th>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script>
$('#ingambar').change(function () {
for (var i=0, len = this.files.length; i < len; i++) {
(function (j, self) {
var reader = new FileReader()
reader.onload = function (e) {
$('tbody').append('<tr><td><img width="100px" src="' + e.target.result + '"></td><input class="form-control" type="text" value="' + self.files[j].name.slice(0, -4) + '" name="namaikan[]" disabled/></td></tr>')
}
reader.readAsDataURL(self.files[j])
})(i, this);
}
});
</script>
</html>
can someone show me how to get it done ?

To achieve this you can sort() the table rows after you append a new one, based on the value of the input contained within the row. Try this:
$('#ingambar').change(function() {
for (var i = 0, len = this.files.length; i < len; i++) {
(function(j, self) {
var reader = new FileReader()
reader.onload = function(e) {
$('tbody').append('<tr><td><img width="100px" src="' + e.target.result + '"></td><td><input class="form-control" type="text" value="' + self.files[j].name.slice(0, -4) + '" name="namaikan[]" disabled/></td></tr>');
sortFiles();
}
reader.readAsDataURL(self.files[j])
})(i, this);
}
});
function sortFiles() {
$('.table tbody tr').sort(function(a, b) {
var $a = $(a).find('input'),
$b = $(b).find('input');
return $a.val().localeCompare($b.val());
}).appendTo('.table tbody');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="flex-center position-ref full-height">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Nama Ikan</h1>
<input id="ingambar" type="file" multiple />
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="content">
<br />
<table class="table">
<thead>
<th>gambar</th>
<th>nama</th>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
</div>

Instead of displaying the images as you read them, you could instead put them all i an array with the same for loop. Then sort the new array with a sort function. And then you just run through the array and display them. Works for me!

You can sort using javascripts Array build in function using a custom sort function with localeCompare. Inserting the following right before the for-loop should do what you want.
this.files.sort((fileA, fileB) => fileA.name.localeCompare(fileB.name));
Providing that this.files is an array of files having a name attribute.

Related

ID of TextArea Undefined-JQuery

I have the following jqueryCode:
$(document).ready(displayItems);
$(document).ready(getAreaIndex);
function displayItems()
{
$.ajax({
type:"GET",
url:"http://tsg-vending.herokuapp.com/items",
success:function(data){
var div = $("#div1");
var html="";
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
for(let i=0;i<data.length;i++)
{
var itemId = data[i].id;
if(i%3==0)
{
html+="<br><br><br><br>";
}
html+='<textarea readonly rows="4" cols="60" style="overflow:hidden" id="' + itemId + '">'+ (i+1) + ' \n ' + data[i].name + ' \n ' + formatter.format(data[i].price) + ' \n Quantity Left: '+ data[i].quantity + '</textarea> ';
}
div.append(html);
//console.log(html);
},
error: function()
{
console.log("Issue");
}
//add error here
});
/*
$("textarea").each(function(){
$text = this.value;
console.log(text);
});
*/
}
function getAreaIndex()
{
console.log($("#21").val());
$("textarea").each(function(){
$text = this.value;
console.log(text.charAt(0));
});
}
I am trying to add textareas dynamically through jquery appending it to a div I have on my html page. The text area id's are generated by an ajax response to a api that functions correctly. The textareas do append correctly on the html page however when trying to print out the textarea values given known IDs it shows undefined. I even try to do a .each through all textareas and it never it even goes in loop. I do this in the getAreaIndex(), printing it to console(id #21 is a valid textarea id generated).
The Following is the html page if needed:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Vending Machine</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- Additional CSS files here -->
</head>
<body>
<div class="container-fluid" id="homeview">
<div class="row">
<div class="col-sm-12">
<h1 style="text-align:center">Vending Machine</h1>
<hr>
</div>
</div>
<div class="row">
<div class="col-sm-9" id="div1">
<!-- Textareas go here -->
</div>
<div class="col-sm-3 float-right" id="Form1">
Total $ In<br>
<input type="text" id="moneyIn"><br><br>
<button id="addDollar">Add Dollar</button>
<button id="addQuarter">Add Quarter</button><br><br>
<button id="addDime">Add Dime</button>
<button id="addNickel">Add Nickel</button>
<hr style="width:30% ;margin-left:0"><br>
Messages<br>
<input type="text" id="messages"><br><br>
Item: <input type="text" id="itemNumber" style="display:block"><br><br>
<button id="makePurchase">Make Purchase</button>
<hr style="width:30% ;margin-left:0"><br>
Change<br><br>
<input type="text" id="change">
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script src="VendingMachine.js"></script>
</body>
</html>
The textareas are inserted after "id=div1"

Function will not update variable

The variable status is set to "uncheck" and needs to be updated to "done" using the change() function.
Ultimately what needs to happen When button with id randomIdTwo is pressed, The completeTodo() function is called which causes the list item to be removed from its current div "list", appended to the div "complete-list", and the change() function updates the value of the "status" variable from "uncheck" to "done".
Everything works except the change() function.
document.getElementById('button').addEventListener('click', function addTodo() {
var value = document.getElementById('input').value;
var status = "uncheck";
var randomId = Math.random();
var randomIdTwo = Math.random();
function change() {
status = "done";
};
const item = `<li>
<div class="item">
<div class="complete">
<button id="` + randomIdTwo + `" class="${status}"></button>
</div>
<p class="text">${value}</p>
<div class="remove">
<button id="` + randomId + `" class="todo"></button>
</div>
</div>
</li>`;
const position = "beforeend";
list.insertAdjacentHTML(position, item);
document.getElementById(randomId).addEventListener('click', function removeTodo() {
var item = this.closest('li');
item.remove();
});
document.getElementById(randomIdTwo).addEventListener('click', function completeTodo() {
var item = this.closest('li');
item.remove();
document.getElementById("completelist").appendChild(item);
change();
});
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="Resources/CSS/reset.min.css">
<link rel="stylesheet" type="text/css" href="Resources/CSS/style.css">
</head>
<body>
<div class="container">
<header>
<div id="datetime"></div>
<div id="ampm"></div>
<input type="text" id="input" placeholder="Add an item" />
<button id="button" type="button"><img src="./img/additem4.png"></button>
</header>
<div id="list">
</div>
<div id="divline"></div>
<div id="completelist">
</div>
</div>
<script src="resources/JS/app.js"></script>
</body>
</html>
Changing the status variable doesn't change the class of the element. You need to update the button's classList
document.getElementById('button').addEventListener('click', function addTodo() {
var value = document.getElementById('input').value;
var status = "uncheck";
var randomId = Math.random();
var randomIdTwo = Math.random();
function change(button) {
button.classList.add("done");
button.classList.remove("uncheck");
};
const item = `<li>
<div class="item">
<div class="complete">
<button id="` + randomIdTwo + `" class="${status}"></button>
</div>
<p class="text">${value}</p>
<div class="remove">
<button id="` + randomId + `" class="todo"></button>
</div>
</div>
</li>`;
const position = "beforeend";
list.insertAdjacentHTML(position, item);
document.getElementById(randomId).addEventListener('click', function removeTodo() {
var item = this.closest('li');
item.remove();
});
document.getElementById(randomIdTwo).addEventListener('click', function completeTodo() {
var item = this.closest('li');
item.remove();
document.getElementById("completelist").appendChild(item);
change(this);
});
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="Resources/CSS/reset.min.css">
<link rel="stylesheet" type="text/css" href="Resources/CSS/style.css">
</head>
<body>
<div class="container">
<header>
<div id="datetime"></div>
<div id="ampm"></div>
<input type="text" id="input" placeholder="Add an item" />
<button id="button" type="button"><img src="./img/additem4.png"></button>
</header>
<div id="list">
</div>
<div id="divline"></div>
<div id="completelist">
</div>
</div>
<script src="resources/JS/app.js"></script>
</body>
</html>
You're using string interpolation to set the class initially, but string interpolation does not create a data-binding between the resultant element and the variable. So change() is being called, and status is being updated, but the value of the element you created via a string isn't seeing that change, so it's not being updated.
You would need to access the element in the DOM and change it's classList manually.

Closures with dynamically generated content

I'm trying to generate an event listener for every element created dynamically. The problem is in the createDisplay function. I'm constantly receiving some errors. I read that the solutions are the closures, but I'm don't understand at this moment. Can anyone help me to learn how to solve this situation?
$(document).ready(function() {
var counter1 = 0;
var counter2 = 0;
// Our Cats
catsArr = [{
name: "Michelangelo",
picture: "img/cat-picture.jpg",
counter: "counter1",
clicks: 0,
listenerClass: "cat-picture-1"
},
{
name: "Ivanka",
picture: "img/cat-picture-2.jpg",
counter: "counter2",
clicks: 0,
listenerClass: "cat-picture-2"
}
];
// Our main function to print the cats
function createDisplay(catsArr) {
for (i = 0; i < catsArr.length; i++) {
$('.cats-place').append(`
<div class=" cat-img col s6 m6 l6 xl5 offset-xl1 center-align">
<p class="cat-1-name flow-text">${catsArr[i].name}</p>
<img class="responsive-img ${catsArr[i].listenerClass}" src="${catsArr[i].picture}" alt="cat picture">
<div class="col s12 m6 offset-m3 center-align">
<p class="flow-text">Counter = <span class="${catsArr[i].counter}">0</span></p>
</div>
</div>`)
$(`.${catsArr[i].listenerClass}`).click(function() {
var counter = 0;
counter = counter + 1;
$(`.${catsArr[i].counter}`).html(counter);
})
}
};
// Executing the function
createDisplay(catsArr)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Cat Clicker</title>
<link rel="stylesheet" href="css\style.css">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
</head>
<body>
<div class="container">
<div class="row cats-place">
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script>
<script src="js\app.js"></script>
</body>
</html>
The issue is that you are trying to reference the i inside the click handler, which has already been iterated to be equal to the length of the array, so it is out of scope. You need to use a closure, or store this variable in another variable, so it is unchanged and preserved for your click handlers.
This modified version uses the forEach method to iterate over the array. An advantage of this is it uses a callback and passes in the element and the index, which for the scope of each call to the callback do not change.
$(document).ready(function() {
var counter1 = 0;
var counter2 = 0;
// Our Cats
catsArr = [{
name: "Michelangelo",
picture: "img/cat-picture.jpg",
counter: "counter1",
clicks: 0,
listenerClass: "cat-picture-1"
},
{
name: "Ivanka",
picture: "img/cat-picture-2.jpg",
counter: "counter2",
clicks: 0,
listenerClass: "cat-picture-2"
}
];
// Our main function to print the cats
function createDisplay(catsArr) {
catsArr.forEach(function(cat) {
$('.cats-place').append(`
<div class=" cat-img col s6 m6 l6 xl5 offset-xl1 center-align">
<p class="cat-1-name flow-text">${cat.name}</p>
<img class="responsive-img ${cat.listenerClass}" src="${cat.picture}" alt="cat picture">
<div class="col s12 m6 offset-m3 center-align">
<p class="flow-text">Counter = <span class="${cat.counter}">0</span></p>
</div>
</div>`)
var counter = 0;
$(`.${cat.listenerClass}`).click(function() {
$(`.${cat.counter}`).html(++counter);
})
});
};
// Executing the function
createDisplay(catsArr)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Cat Clicker</title>
<link rel="stylesheet" href="css\style.css">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
</head>
<body>
<div class="container">
<div class="row cats-place">
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script>
<script src="js\app.js"></script>
</body>
</html>

Ajax call : ReferenceError: url is not defined

MY js code :
function OrderFormControllerForRE($scope, $http) {
var urlString = window.location.href;
var urlParams = parseURLParams(urlString);
var jsonData = $.ajax({
url: "http://******:8989/getRuleEngine",
dataType: "json",
crossDomain: true,
}).responseText;
debugger;
if (!jsonData || jsonData === "") {
window.location.pathname = "../html/noDataFetched.html";
}
var parsed = JSON.parse(jsonData);
if (parsed.error) {
window.location.pathname = "../html/error.html";
}
$scope.ruleEngineJSON = parsed;
$scope.ruleName = "";
$scope.priority = "";
$scope.modifyPriority = function(ruleName) {
$scope.ruleName = ruleName;
$scope.priority = $scope.ruleEngineJSON[ruleName];
};
};
function navigateRuleEngine() {
window.location.pathname = "../html/modifyRuleEngine.html";
}
function parseURLParams(url) {
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1),
pairs = query.replace(/\+/g, " ").split("&"),
parms = {}, i, n, v, nv;
if (query === url || query === "") return;
for (i = 0; i < pairs.length; i++) {
nv = pairs[i].split("=", 2);
n = decodeURIComponent(nv[0]);
v = decodeURIComponent(nv[1]);
if (!parms.hasOwnProperty(n)) parms[n] = [];
parms[n].push(nv.length === 2 ? v : null);
}
return parms;
}
My Html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>POC-SalesForce</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.min.js"></script>
<img src="../img/spinner.gif" id="img" style="display:none"/>
<link href="https://fonts.googleapis.com/css?family=Cookie|Open+Sans:400,700" rel="stylesheet"/>
<!-- The main CSS file -->
<link href="../css/style.css" rel="stylesheet"/>
<link href="../css/codeReview.css" rel="stylesheet"/>
<link rel="stylesheet prefetch" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet prefetch" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.min.css">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="../css/preloader.css">
<script src="../js/scriptRuleEngine.js"></script>
</head>
<body ng-app ng-controller="OrderFormControllerForRE">
<header>
<div class="container">
<div id="branding">
<h1><span class="highlight">Modify Rule Engine </span></h1>
</div>
</div>
</header>
<section class="col-md-12 col-lg-12 dateSection">
<!--<form method="get">-->
<table id="ruleEngine" class="table table-sm table-inverse table-responsive table-striped table-bordered"
cellpadding="20" width="100%">
<thead>
<tr>
<th>Rule Name</th>
<th>Priority</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr ng-repeat="(key,value) in ruleEngineJSON">
<td>{{key}}</td>
<td>{{value}}</td>
<td><button type="button" class="btn btn-default"
ng-click="modifyPriority(key)">Modify</button></td>
</tr>
</tfoot>
</table>
<!--</form>-->
</section>
<footer>
<p>Salesforce Free Code Review For Syngenta, Copyright © 2017</p>
<p>Developed By - Nagendra Kumar Singh</p>
</footer>
</body>
</html>
When I load the page the url fires the controller and return the correct JSON format as I can see the results directly in the browser by accessing http://********:8989/getRuleEngine
But when the page is loaded I get this error in the JS while debugging:
"ReferenceError: url is not defined
at eval (eval at OrderFormControllerForRE (http://usblrnagesingh1:8989/js/scriptRuleEngine.js:12:9), <anonymous>:1:1)
at c.OrderFormControllerForRE (http://usblrnagesingh1:8989/js/scriptRuleEngine.js:12:9)
at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.min.js:35:36)
at Object.instantiate (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.min.js:35:165)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.min.js:68:194
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.min.js:54:298
at r (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.min.js:7:392)
at K (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.min.js:54:163)
at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.min.js:47:397)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.min.js:47:17"
enter image description here
I dont know why is it failing because I have a similar page which has <body ng-app ng-controller="OrderFormController"> and the script has function OrderFormController($scope, $http) {}. It works fine there without any error.
Update
I have even tried changing the angular js version, but that does not work. Also this version should work as I have similar page which is working.

Iterate through a JSON list with JS function

I'm looking for a way to append some JSON results, I'm working with a list (array?) and there's multiple elements, I know I can add some styling directly in the JS code but I'm more comfortable with this method. How can I iterate through elements and implement in some divs, then create similar divs with the next elements.
The only way to achieve that goal afaik is like this:
$("#article").append(data[i].datetime + data[i].headline + "<br />" + "<hr />" + data[i].summary);
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Project JS 02</title>
<link rel="stylesheet" href="assets/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div class="container container-table">
<div class="row vertical-center-row">
<div class="col-md-4 col-md-offset-4">
<button type="submit" class="btn btn-primary" style="width: 100%" class="search" id="getnews">Get News!</button>
<h1 id="headline"></h1><br>
<h3 id="datetime"></h3><br>
<div id="summary"></div><br>
<h6 id="source"></h6><br>
</div>
</div>
</div>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script>
document.getElementById("getnews").addEventListener("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$.getJSON(newsurl, function (data) {
for (i in data)
{
$("#headline").append(data[i].headline);
$("#datetime").append(data[i].datetime);
$("#summary").append(data[i].summary);
$("#source").append(data[i].source);
}
})
})
</script>
</body>
</html>
You can do this by creating the elements (with jQuery) as needed, and appending them to a container:
$("#getnews").on("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$('#data').text("...loading...");
$.getJSON(newsurl, function (data) {
$('#data').html("");
data.forEach(function (article) {
$('#data').append(
$('<h1>').text(article.headline),
$('<h3>').text(article.datetime),
$('<div>').text(article.summary),
$('<h6>').text(article.source)
);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn btn-primary search"
style="width: 100%" id="getnews">Get News!</button>
<div id="data"></div>
First: remove the ids. If you want to create similar containers, the ids will be there multiple times, that won't work.
Second: Take the div with $('.row.vertical-center-row') and clone it.
Third: set the values at the cloned HTMLNode und append it to $('.container.container-table')
Something like that (untested):
<div class="container container-table">
<div class="row vertical-center-row">
<div class="col-md-4 col-md-offset-4">
<button type="submit" class="btn btn-primary" style="width: 100%" class="search" class="getnews">Get News!</button>
<h1 class="headline"></h1><br>
<h3 class="datetime"></h3><br>
<div class="summary"></div><br>
<h6 class="source"></h6><br>
</div>
</div>
</div>
<script>
document.getElementsByClassName("getnews").forEach((el)=>el.addEventListener("click", function () {
var newsurl = "https://api.iextrading.com/1.0/stock/aapl/news"
$.getJSON(newsurl, function (data) {
var $elClone = $('.row.vertical-center-row').clone(true).appendTo($('.container.container-table'));
for (i in data) {
$(".headline", $elClone).append(data[i].headline);
$(".datetime", $elClone).append(data[i].datetime);
$(".summary", $elClone).append(data[i].summary);
$(".source", $elClone).append(data[i].source);
}
})
}));
</script>

Categories

Resources