Currently, I am trying to draw a table using jQuery but its not working. This is the current js code. I tried using append but it didnt work for the table. Can someone help me on this. Thank you.
(function(){
var location = new Array();
var query = '%23CM0655';
var url = "search.php";
$.post(url, {query:query}, function(tweets){
console.log(tweets);
$("#tweetResult").html("");
var geoEnabled = false;
var placeName = "";
var countryName = "";
for(var i=0; i<tweets.statuses.length; i++){
var img = $("<img src='" + tweets.statuses[i].user.profile_image_url + "' class='tweetpic'/>");
$("#tweetResult").append(img);
$("#tweetResult").append('<br/>');
$("#tweetResult").append(tweets.statuses[i].user.screen_name);
$("#tweetResult").append(tweets.statuses[i].text + "<br/>");
geoEnabled = tweets.statuses[i].user.geo_enabled;
if(geoEnabled){
placeName = tweets.statuses[i].place.name;
countryName = tweets.statuses[i].place.country;
if(placeName != null){
$("#tweetResult").append(placeName + ", ");
$("#tweetResult").append(countryName + "<br/>");
}
$("#tweetResult").append("Location: " + tweets.statuses[i].place.bounding_box.coordinates[0][0][0] + ", ");
$("#tweetResult").append(tweets.statuses[i].place.bounding_box.coordinates[0][0][1] + "<br/>");
$("#tweetResult").append(tweets.statuses[i].created_at);
}
$("#tweetResult").append("<br/><br/>");
}
});
setTimeout(arguments.callee, 10000);
})();
Currently this is the output which i am getting after using the append method to create the table
<div id="here_table">
<table> </table> !!!!!!!!!!
<tr><td>result1</td></tr>
<tr><td>result2</td></tr>
<tr><td>result3</td></tr>
</div>
I replicated the issue with some sample data (didn't use every property). But this'll show you how it's done.
Just run the snippet below or check this fiddle out
var tweets = {
statuses: [{
place: {
name: "Oostend",
country: "Belgium"
},
user: {
profile_image_url: "https://jsfiddle.net/img/logo.png",
screen_name: "John Doe",
geo_enabled: true
},
text: "Hello world!",
created_at: "April 7th 2016"
}, {
place: {
name: "Veurne",
country: "Belgium"
},
user: {
profile_image_url: "https://jsfiddle.net/img/logo.png",
screen_name: "Jane Doe",
geo_enabled: false
},
text: "Geo is disabled for me",
created_at: "April 6th 2016"
}]
}
$("#tweetResult").html("");
var table = $("<table></table>");
var thead = $("<thead></thead>");
thead.append($("<th></th>").html("Some header"));
var tbody = $("<tbody></tbody>");
var geoEnabled = false;
var placeName = "";
var countryName = "";
for (var i = 0; i < tweets.statuses.length; i++) {
var row = $("<tr></tr>");
var img = $("<td><img src='" + tweets.statuses[i].user.profile_image_url + "' class='tweetpic'/><br/></td>");
row.append(img);
row.append($("<td></td>").html(tweets.statuses[i].user.screen_name));
row.append($("<td></td>").html(tweets.statuses[i].text + "<br/>"));
geoEnabled = tweets.statuses[i].user.geo_enabled;
if (geoEnabled) {
placeName = tweets.statuses[i].place.name;
countryName = tweets.statuses[i].place.country;
if (placeName != null) {
row.append($("<td></td>").html(placeName + ", " + countryName));
}
//row.append($("<td></td>").html("Location: " + tweets.statuses[i].place.bounding_box.coordinates[0][0][0] + ", " + tweets.statuses[i].place.bounding_box.coordinates[0][0][1] + "<br/>"));
row.append($("<td></td>").html(tweets.statuses[i].created_at));
}
tbody.append(row);
}
table.append(thead).append(tbody);
$("#tweetResult").append(table);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tweetResult">
</div>
EDIT
I edited the code to your current situation, where as a <table></table> element is created from scratch.
Related
When creating new div with data from input form, the first div save the data that i inputed, but next, when i input new data, div display undefined value.
first attempt second attempt
0: {name: "Milk", amount: "30"}
name: "Milk"
amount: "30"
1: "expense"
2: "expense"
3: "expense"
document.getElementById('expenseInput').addEventListener('submit', saveExpense);
function saveExpense(e) {
let expenseName = document.getElementById('expenseNameInput').value,
expenseAmount = document.getElementById('expenseAmountInput').value;
let expenseStorage = {
name: expenseName,
amount: expenseAmount,
}
if (localStorage.getItem('expenses') == null) {
let expenses = [];
expenses.push(expenseStorage);
localStorage.setItem('expenses', JSON.stringify(expenses));
} else {
let expenses = JSON.parse(localStorage.getItem('expenses'));
expenses.push('expenseStorage');
localStorage.setItem('expenses', JSON.stringify(expenses));
}
document.getElementById('expenseInput').reset();
fetchExpense();
e.preventDefault();
}
function fetchExpense() {
let expenses = JSON.parse(localStorage.getItem('expenses')),
expensesList = document.getElementById('expensesList');
expensesList.innerHTML = '';
for (let i = 0; i < expenses.length; i++) {
let name = expenses[i].name,
amount = expenses[i].amount;
expensesList.innerHTML += '<div class="well" id="expense-item">' +
'<h3>' + name + '</h3>' +
'<h3>' + amount + '</h3>' +
'Delete' +
'</div>';
}
}
I'm rewriting code many times but it doesnt's work.
Try replacing expenses.push('expenseStorage') to expenses.push(expenseStorage).
So your code will look like this:
document.getElementById('expenseInput').addEventListener('submit', saveExpense);
function saveExpense(e) {
let expenseName = document.getElementById('expenseNameInput').value,
expenseAmount = document.getElementById('expenseAmountInput').value;
let expenseStorage = {
name: expenseName,
amount: expenseAmount,
}
if (localStorage.getItem('expenses') == null) {
let expenses = [];
expenses.push(expenseStorage);
localStorage.setItem('expenses', JSON.stringify(expenses));
} else {
let expenses = JSON.parse(localStorage.getItem('expenses'));
expenses.push(expenseStorage);
localStorage.setItem('expenses', JSON.stringify(expenses));
}
document.getElementById('expenseInput').reset();
fetchExpense();
e.preventDefault();
}
function fetchExpense() {
let expenses = JSON.parse(localStorage.getItem('expenses')),
expensesList = document.getElementById('expensesList');
expensesList.innerHTML = '';
for (let i = 0; i < expenses.length; i++) {
let name = expenses[i].name,
amount = expenses[i].amount;
expensesList.innerHTML += '<div class="well" id="expense-item">' +
'<h3>' + name + '</h3>' +
'<h3>' + amount + '</h3>' +
'Delete' +
'</div>';
}
}
I am attempting to build a 9 divs (cards) dynamically containing information about store branch locations. Each card has a unique URL associated with it that links to each branches specific URL.
This approach, within the function, appends the first (0) URL to all the cards:
$("div").click(function() {
window.location = $(this).find("a").attr("href");
return false;
});
This approach appends the last URL (8) to all the cards:
branch.addEventListener("click", function(e){
e.preventDefault();
window.open(prop.pages_url);
})
Code I'm working with:
function buildLocationList(data) {
for (i = 0; i < 9; i++) {
var currentFeature = data.features[i];
var prop = currentFeature.properties;
//Create Card
var branches = document.getElementById('branches');
var url = branches.appendChild(document.createElement('a');
url.setAttribute('href', prop.pages_url);
)
var branch = branches.appendChild(document.createElement('div'));
branch.className = 'card';
branch.id = "branch-" + i;
branch.url = prop.pages_url;
branch.addEventListener("click", function(e){
e.preventDefault();
window.open(prop.pages_url);
})
//Append Branch Card Details
v
var company = branch.appendChild(document.createElement('h5'));
company.innerHTML = prop.name + '<br />';
var distancePhone = branch.appendChild(document.createElement('p'));
if (prop.distance) {
var roundedDistance = Math.round(prop.distance * 100) / 100;
distancePhone.innerHTML = '<span class="miles">Approx. ' + roundedDistance + ' miles</span>' + '<span class="location-phone">' + prop.phone_number + '</span>';
}
else {
distancePhone.innerHTML = prop.phone_number;
}
var address = branch.appendChild(document.createElement('p'));
if (prop.address_line_2) {
address.innerHTML += prop.address_line_1 + ', ' + prop.address_line_2 + '<br />';
}
else {
address.innerHTML += prop.address_line_1 + '<br />';
};
address.innerHTML += prop.address_city + ', ' + prop.address_state + ' ' +prop.address_postal_code + '</p>';
}
}
I would like the card to be clickable with a redirect to each branch's unique URL.
You're storing the URL on the card element:
branch.url = prop.pages_url
All you need to do in the click handler is access the property:
branch.addEventListener("click", function(e){
e.preventDefault();
window.open(e.currentTarget.url);
})
In the context of the event handler, e.currentTarget is the element to which the handler is attached. If you were interested in which element fired the event, you'd use e.target.
Here's your code snippet modified below. I don't think the links will open on here though due to the sandboxed iframe.
function buildLocationList(data) {
for (i = 0; i < data.features.length; i++) {
var currentFeature = data.features[i];
var prop = currentFeature.properties;
//Create Card
var branches = document.getElementById('branches');
var url = branches.appendChild(document.createElement('a'));
url.setAttribute('href', prop.pages_url);
var branch = branches.appendChild(document.createElement('div'));
branch.className = 'card';
branch.id = "branch-" + i;
branch.url = prop.pages_url;
branch.addEventListener("click", function(e){
e.preventDefault();
console.log(e.currentTarget.url);
window.open(e.currentTarget.url);
})
//Append Branch Card Details
var company = branch.appendChild(document.createElement('h5'));
company.innerHTML = prop.name + '<br />';
var distancePhone = branch.appendChild(document.createElement('p'));
if (prop.distance) {
var roundedDistance = Math.round(prop.distance * 100) / 100;
distancePhone.innerHTML = '<span class="miles">Approx. ' + roundedDistance + ' miles</span>' + '<span class="location-phone">' + prop.phone_number + '</span>';
}
else {
distancePhone.innerHTML = prop.phone_number;
}
var address = branch.appendChild(document.createElement('p'));
if (prop.address_line_2) {
address.innerHTML += prop.address_line_1 + ', ' + prop.address_line_2 + '<br />';
}
else {
address.innerHTML += prop.address_line_1 + '<br />';
};
address.innerHTML += prop.address_city + ', ' + prop.address_state + ' ' +prop.address_postal_code + '</p>';
}
}
buildLocationList({features:[{
properties: {
distance: 100,
name: 'Google',
pages_url: 'https://www.google.com',
phone_number: '123-456-7890',
address_line_1: '1234 Street',
address_city: 'Citytown',
address_state: 'State',
address_postal_code: '12345'
}
},{
properties: {
distance: 200,
name: 'Microsoft',
pages_url: 'https://www.microsoft.com',
phone_number: '123-456-7890',
address_line_1: '1234 Street',
address_city: 'Citytown',
address_state: 'State',
address_postal_code: '12345'
}
}]})
.card {
border: 1px solid #ccc;
padding: 10px;
max-width: 50%;
margin: 10px;
}
<div id="branches"></div>
<div>
w3schools
</div>
<script>
$("div").click(function() {
window.location = $(this).find("a").data("value");
});
</script>
In the following code pen you can see that I have setup a factory that takes in an array of Objects as data, loops through that data and then add's button's into the page with an onclick event that logs out the data object.
const testData = [{
fruit: 'Banana'
},
{
fruit: 'Apple'
},
{
fruit: 'Pear'
}
];
const scopeCreep = ({
data
}) => {
const outputDiv = document.getElementById('output');
const getID = () => {
return Math.random().toString(36).substring(7);
};
var lastID;
for (let x = 0; x < data.length; x++) {
data[x].ID = getID();
lastID = data[x].ID;
}
//Add a button to the test div
let button = document.createElement('button');
button.innerText = lastID;
button.onclick = () => {
console.log(privateData, lastID);
outputDiv.innerHTML += "Click resulted in: </br>";
outputDiv.innerHTML += "Array data: " + JSON.stringify(data, null, 2) + ", lastID: " + lastID + "</br>";
};
document.body.appendChild(button);
//JSON parse hack
var privateData = JSON.parse(JSON.stringify(data, null, 2));
//Add new IDS and choose a random one to output as selection
return {
privateData,
data
};
};
const tester = () => {
const outputDiv = document.getElementById('output');
var data1 = scopeCreep({
data: testData
});
outputDiv.innerHTML += "1 load: " + JSON.stringify(data1.privateData, null, 2) + " - " + JSON.stringify(data1.data, null, 2) + "</br>";
var data2 = scopeCreep({
data: testData
});
outputDiv.innerHTML += "2 load: " + JSON.stringify(data2.privateData, null, 2) + " - " + JSON.stringify(data2.data, null, 2) + "</br>";
var data3 = scopeCreep({
data: testData
});
outputDiv.innerHTML += "3 load: " + JSON.stringify(data3.privateData, null, 2) + " - " + JSON.stringify(data3.data, null, 2) + "</br>";
};
document.addEventListener("DOMContentLoaded", tester);
<div id="test">
</div>
<div id="output">
</div>
It seems that the data is being overridden with the last loaded data. (I hope that makes sense?)
My question boils down to: Why is this data being changed out of scope & how can I stop it?
Thanks,
you have to put this line var privateData = JSON.parse(JSON.stringify(data, null, 2)); at the top of the function in order to clone it before modify the original object
I am cloning the data in scope using the following, thankfully the data does not contain any functions as the following would not replicate functions.
JSON.parse(JSON.stringify(data));
I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>
I'm trying to pull out data from my json using match() in my search function. Here's what I want to do using the string inputted in the textbox. It would then pull out data from my json array as long as there is a match. Here's what I have so far:
var data = [{
"RM_Name": "Russ Martin",
"Division": "East",
"RM_Phone": "(603) 491-1259",
"RC_Name": "Jacob Sucoff",
"RC_Phone": "(800) 247-4154 x3403",
"States_Covered": "MT,VT, NH, ME (all firms)",
"Latitude": 46.6797995,
"Longitude": -110.044783,
"Coordinates": "46.6797995,-110.044783"
}, {
"RM_Name": "Carey Fortnam",
"Division": "East",
"RM_Phone": "(585)-259-7394",
"RC_Name": "Matt Wrzesniewsky",
"RC_Phone": "(800) 247-4154 x3088",
"States_Covered": "NY- Upstate ex Rockland County (BD, FP)",
"Latitude": 40.7056308,
"Longitude": -73.9780035,
"Coordinates": "40.7056308,-73.9780035"
}];
$.each(data, function(i, item) {
var rm_name = item.RM_Name,division = item.Division,rm_phone = item.RM_Phone,rc_name = item.RC_Name,rc_phone = item.RC_Phone,states = item.States_Covered;
var dataset='<tr class="'+rm_name+' '+rc_name+'"><td>'+rm_name+'</td><td>'+division+'</td><td>'+rm_phone+'</td><td>'+rc_name+'</td><td>'+rc_phone+'</td><td>'+states+'</td></tr>';
$('.rm-data').append(dataset);
});
$('#search').on('keypress', function (e) {
if(e.which == 13) {
search();
}
}).on('change', function (e) {
search();
});
function search() {
var query = $('#search').val();
// empty?
if(query === "")
{
$('.rm-data tr').show();
return;
}
$('.rm-data tr').hide();
$('.error-msg').hide();
if ($('.rm-data tr').hasClass(query)) {
$('.rm-data tr:contains(' + query + ')').fadeIn('slow', function () {
$('.rm-data tr:contains(' + query + ')').slideDown().show();
});
}
else {
//JSON Match Finder
$.getJSON(data, function (data) {
$.each(data, function (i, item) {
var test= item.RM_Name+' '+item.RC_Name;
var regex = new RegExp(query);
var test2 = test.match(regex);
console.dir(test2);
});
});
var error = '<div class="error-msg">Contact Not Found</div>';
$('.rm-table-search').append(error);
if ($('.error-msg').length == 0) {
$('.rm-table').append(error);
}
else {
$('.rm-table').append('');
}
}
}
I am able to find matches using this code but I cannot pull the data out. Is there anyway I can do this? Fiddle here.
Just sharing my output so far via console.log()
["Ru", index: 0, input: "Russ MartinJacob Sucoff", $family: function, $constructor: function, pop: function…]
ab-rm.js:80
6
null ab-rm.js:80
["Ru", index: 18, input: "Kevin GangMichael Rus", $family: function, $constructor: function, pop: function…]
ab-rm.js:80
12
null ab-rm.js:80
["Ru", index: 0, input: "Russ CorbyNatasha Fomenko", $family: function, $constructor: function, pop: function…]
ab-rm.js:80
8
null ab-rm.js:80
["Ru", index: 6, input: "Laura RupsisKenny Meyer", $family: function, $constructor: function, pop: function…]
I figured it out based on balexandre's idea:
$.each(data, function (i, item) {
var rm_name = item.RM_Name,
division = item.Division,
rm_phone = item.RM_Phone,
rc_name = item.RC_Name,
rc_phone = item.RC_Phone,
states = item.States_Covered;
var dataset = '<tr class="' + rm_name + ' ' + rc_name + '"><td>' + rm_name + '</td><td>' + division + '</td><td>' + rm_phone + '</td><td>' + rc_name + '</td><td>' + rc_phone + '</td><td>' + states + '</td></tr>';
$('.rm-data').append(dataset);
});
function search() {
var query = $('#search').val();
$('.rm-data tr').hide();
$('.error-msg').hide();
if ($('.rm-data tr').hasClass(query)) {
$('.rm-data tr:contains(' + query + ')').fadeIn('slow', function () {
$('.rm-data tr:contains(' + query + ')').slideDown().show();
});
} else {
var combined_array = [];
$.each(data, function (i, item) {
combined_array.push(item.RM_Name);
combined_array.push(item.RC_Name);
});
$.each(combined_array, function (i, item) {
var contents = item;
var array_check = item.indexOf(query) >= 0;
var matches = ''+contents+'';
$('#search-helper-container').append(matches);
$('.false').remove();
$('#search-helper-container').css('display', 'block');
});
var error = '<div class="error-msg">Contact Not Found</div>';
$('.rm-table-search').append(error);
if ($('.error-msg').length == 0) {
$('.rm-table').append(error);
} else {
$('.rm-table').append('');
}
}
}
$('#search-button').on('click', function () {
search();
});
$('#search').on('focus', function () {
$('#search').val('');
$('.true').remove();
$('#search-helper-container').css('display', 'none');
});
$('#search-helper-container').on('click', 'a.search-match', function (e) {
e.preventDefault();
var inputVal = $(this).text();
$('#search').val(inputVal);
});
And a working Fiddle here.