Parsing data using JQuery - javascript

I have a container that has a Google maps API on one tab and images on another. When a location is selected from a list, I want to image to change in the other tab.
I have a hidden input field which stores a list of locations with ID's and images. When a list item is clicked on, there's a div which has the ID.
It looks like this:
<input id="storeLocatorData" name="storeLocatorData" type="hidden" value="[{"id":2,"name":"name","lat":51.111113,"lng":-1.3111121,"category":"test","address":"Company 1","address2":"Test Road","address3":"","city":"Bristol","postal":"B90 5BD","country":"UK","phone":"","email":{},"image":"1181","LocationPhoto":"http://url/media/2728/logo.png"},{"id":3,"name":"name","lat":51.1113243,"lng":-1.331121,"category":"test","address":"Company 1","address2":"Test Road","address3":"","city":"Bristol","postal":"B90 5BD","country":"UK","phone":"","email":{},"image":"1181","LocationPhoto":"http://url/media/2728/header.png"}]/>
I want to find the text of the div (ID) then find the associated image from the list, then set the src of the image to the new selected image.
How would I parse the list and grab the url in image based on #loc-id text and then set #location-image?
Here's what I have so far:
$('#list').click(function () {
//Change the src of img
$(this).find('#loc-id').text();
$('#location-image').attr('src', newVal);
});
Here's the full HTML:
<div id="map-container">
<div class="tabs mobile-hide">
<ul class="tab-links">
<li class="active"><a class="tab-link-text" href="#tab1">Location Map</a></li>
<li><a class="tab-link-text" href="#tab2">Location Photo</a></li>
</ul>
<div class="tab-content">
<div id="tab1" class="tab active">
<div id="panel-map">
<div id="map"></div>
</div>
</div>
<div id="tab2" class="tab">
<img id="location-image" class="location-photo" src=""/>
</div>
</div>
</div>
</div>
var jsonMarkers = new List<object>
();
foreach (dynamic l in this.Locations)
{
var media = Model.MediaById(l.image);
jsonMarkers.Add(new
{
id = l.LocationId,
name = l.address1,
lat = l.latitude,
lng = l.longitude,
address = l.address1,
address2 = l.address2,
address3 = l.address3,
city = l.city,
postal = l.postcode,
country = "UK",
phone = l.telephoneNumber,
email = l.bookingAfterEmail,
image = l.image,
LocationPhoto = url + media.NiceUrl
});
}
#Html.Hidden("storeLocatorData", Json.Encode(jsonMarkers));
Thanks!

You can parse the array with JSON, as such:
// Store a parsed array
var parsedArray = JSON.parse(document.getElementById('storeLocatorData').value);
// When we select the item
$('#list').click(function () {
//Change the src of img
var targetID = $(this).find('#loc-id').text(); // Get the ID
// Since your array of objects isn't indexed, we need to loop to find the correct one
var foundObject = null;
for (var key in parsedArray) {
if (parsedArray.hasOwnProperty(key) && parsedArray[key].id == targetID) {
foundObject = parsedArray[key];
break;
}
}
// If we found the object, extract the image and set!
if (!foundObject)
return;
var imageSrc = foundObject.LocationPhoto; // From the object
$('#location-image').attr('src', imageSrc); // Set the new source
});

Related

adding a date to the items in the list and displaying them on a webpage

I am completely lost on a task where I have to add a date to the items when they are created, store them in a list and then present on my webpage.
my javascript code
var counter=4;
var completelist = document.getElementById("thelist");
var currentTime = new Date();
todo=[todo1,todo2,todo3];
todoButton.onclick=function addelement() {
var userTodoInput = document.getElementById("todoInput");
if(userTodoInput.value!=="" ){
let node = document.createElement("LI");
node.innerHTML = userTodoInput.value;
completelist.appendChild(node);
todo.push(userTodoInput);
document.getElementById("mydiv").innerHTML += "<div class='todo' ><p id='t-list'> You have added this to the list of actions: " + userTodoInput.value + "</p></br></div>";
} else {
alert("Enter something in textarea")
}
counter++;
}
My dom
<div class="todo-container" >
<h1 class="about-heading">The todo list </h1>
<p id="todo-paragraph">On this page you are able to add new items to your to-do list </p>
<div class="todo-items">
<ul id="thelist">
<li class="todo"id="todo1">Item 1</li>
<li class="todo" id="todo2">Item 2</li>
<li class="todo" id="todo3"> Item 3</li>
</ul>
<input id="todoInput" type="text" name="todoInput" placehoder="Type your to-do here">
<button id="todo-button" >Add Item </button>
<div id="mydiv">
</div>
</div>
what would you suggest on this?
The problem is, your todoButton is not defined anywhere in your code.
If you add var todoButton = document.getElementById("todo-button");, your script should be working.
EDIT:
If you want to append date to user input, check edited code below. I stored userTodoInput and currentTime to single variable, named newItem and then place the variable on places you need it. I hope this help.
var counter = 4;
var completelist = document.getElementById("thelist");
var currentTime = new Date();
todo = [todo1, todo2, todo3];
todoButton.onclick = function addelement() {
var userTodoInput = document.getElementById("todoInput");
if (userTodoInput.value !== "") {
let node = document.createElement("LI");
let newItem = `${userTodoInput.value} ${currentTime}`;
node.innerHTML = newItem;
completelist.appendChild(node);
todo.push(newItem);
document.getElementById("mydiv").innerHTML += "<div class='todo' ><p id='t-list'> You have added this to the list of actions: " + newItem + "</p></br></div>";
} else {
alert("Enter something in textarea")
}
counter++;
Take a look to the following commented code. Obviously it is a basic implementation, but I think that main concepts are clear:
// GET ELEMENTS.
const list = document.getElementById('list');
const input = document.getElementById('input');
const button = document.getElementById('button');
const onClickHandler = () => {
// CHECK FOR TO-DO NAME.
if (input.value) {
// USE ELEMENT CHILDREN COUNT AS INDEX.
const index = list.children.length;
// CREATE li ELEMENT PROGRAMMATICALLY.
const li = document.createElement('LI');
// INSTANTIATE A NEW DATE OBJECT.
const date = new Date();
// ADD ATTRIBUTES.
li.id = `todo${index}`;
li.class = 'todo';
li.innerText = `${input.value} - ${date.toString()}`;
// ADD ELEMENT TO DOM.
list.appendChild(li);
} else {
alert('Please type your to-do.')
}
};
// ADD EVENT LISTENER.
button.addEventListener('click', onClickHandler);
<div>
<h1>The todo list</h1>
<p>On this page you are able to add new items to your to-do list</p>
<div>
<ul id="list"></ul>
</div>
<input id="input" type="text" name="todo" placeholder="Type your to-do here">
<button id="button" type="button">Add Item</button>
</div>

How to populate an array with indexOf

I'm trying to populate an array with the output of my for loop.
In this case, I'm trying to push every result where indexOf does not return -1 in that showArray.
Here's an example of li I want to push in the array.
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="https://randomuser.me/api/portraits/thumb/women/12.jpg">
<h3>soline leclercq</h3>
<span class="email">soline.leclercq#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 05/12/14</span>
</div>
</li>
Here is the Javascript
var showArray = [];
for (var i = 0; i < eachStudent.length; i++) {
var studentName = document.getElementsByTagName("h3");
var studentInfo = studentName[i].innerText;
var filter = inputString.value.toUpperCase();
if (studentInfo.toUpperCase().indexOf(filter) != -1) {
showArray.push(eachStudent[i]);
}
console.log(showArray);
}
So far, the showArray.push(eachStudent[i]) is not working, it's not printing the items to the array. My goal is to fill and empty that array dynamically as the user types in the search bar.

how to display name from firebase

I have this part of my code and I am trying to have the user name display from firebase when a user comes to map. but when I run the code it erase all the html and prints 2 lines of code :
5Frederick619
•5Profile-10
essentially erasing all my code
<!--you can-->
<div class="row">
<div class="col-md-12 youcan">
<h4>You can:</h4>
<ul>
<li><span>1</span> Track the location your friends my brother</li>
<li><span>2</span> Track the location your friends my brother</li>
<li><span>3</span> Track the location your friends my brother</li>
<li><span>4</span> Track the location your friends my brother</li>
<script>
var endpoint;
endpoint = new Firebase('https://keepitstreet.firebaseio.com/maps/openmap');
endpoint.on('child_added', function(childSnapshot) {
var uuid = childSnapshot.key()
var point = childSnapshot.val()
var username = childSnapshot.val();
var name = username.name;
document.write('<li><span>5</span>'+ name +'</li>');
})
</script>
</ul>
</div>
</div>
<!--/you can-->
document.write is meant to be used when opening a new window and inserting content into it, so when called on a loaded document, it will clear it. that's why your entire html is being deleted, except for the last thing your writing to the document.
what you need is to add the new item. you could do something like this:
function getPosts() {
var endpoint;
var list = document.querySelector('.youcan ul');
endpoint = new Firebase('https://keepitstreet.firebaseio.com/maps/openmap');
endpoint.on('child_added', function(childSnapshot) {
var uuid = childSnapshot.key()
var point = childSnapshot.val()
var username = childSnapshot.val();
var name = username.name;
appendPosts(name)
})
function appendPosts(name) {
var li = document.createElement('li');
li.textContent = name;
list.appendChild(li);
}
}

jQuery How to use a ID grabbed from a clicked div

I have a people section on a website I'm building which uses isotope for filtering. When I click on a person I want to show their full info on the right. When the click happens I grab the id and store it as a variable. I then have variables named to match up with the grabbed IDs.
How do I use the grabbed ID to target the variables stored in my js file? Currently it only prints out the ID grabbed from the clicked div.
var userOne = "<p>userOne info<p>";
var userTwo = "<p>userTwo info<p>";
var userThree = "<p>userThree info<p>";
$('.item').on("click", function(){
var id = $(this).attr('id'); // this grabs the ID of the div eg userOne
var printId = id; //trying to change the variable so I can use it
$('.bio').html(printID); //this is where it should print out
});
You can't access a variable name like that, instead what you can do is to access a object's property with a dynamic key
Assuming the variables userOne/userTwo are in the global scope, you can use the bracket notation like
var userOne = "<p>userOne info<p>";
var userTwo = "<p>userTwo info<p>";
var userThree = "<p>userThree info<p>";
$('.item').on("click", function () {
var printId = window[this.id];
$('.bio').html(printID);
});
another option is to store those values as properties of an object
var user = {
userOne: "<p>userOne info<p>",
userTwo: "<p>userTwo info<p>",
userThree: "<p>userThree info<p>"
};
$('.item').on("click", function () {
var printId = user[this.id];
$('.bio').html(printID);
});
Try
html
<div class="item" data-user="<p>userOne info<p>"></div>
js
$(".item").on("click", function(e) {
$(".bio").html($(this).data("user"))
})
$(".item").on("click", function(e) {
$(".bio").html($(this).data("user"))
})
div:not(.bio) {
border:1px dotted grey;
width: 24px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="item" data-user="<p>userOne info<p>">1</div><br />
<div class="item" data-user="<p>userTwo info<p>">2</div><br />
<div class="item" data-user="<p>userThree info<p>">3</div><br />
<div class="bio"></div>

How to get text from span->li->ul-> Element

Hello i have cart full with Elements
This Ex of one of them
<div class="item-container cart-item">
<div>
<img border="0" onerror="src='http://www.myengravedjewelry.com/Admin/surfing.jpg'" title="Bloody Mary Style Colour Name Necklace" src="http://www.myengravedjewelry.com/Admin/surfing.jpg" alt="1009">
<div class="item-header">
<div class="item-body">
<ul class="item-ul">
<li>
<li>
<li>
<span class="bold-14">Price:14.9 </span>
</li>
<li>
<span>ShortId:1010 </span>
</li>
<li>
<span>LongId:110-01-073-10 </span>
</li>
<li>
<span class="spanDefCat">DefaultCat:334 </span>
</li>
</ul>
</div>
</div>
<div class="item-footer"></div>
</div>
When i press save i go trow each one of this element and check if DefaultCat==0
var elements = document.getElementsByClassName("cart-item");
and i try to get to this defaulCat like this
for(i=0;i<elements.length;i++){
var elementContent=elements[i].find(".spanDefCat").html();
var vars = elementContent.split(" ");
var obj = {};
vars.forEach(function(v) {
var keyValue = v.split(":");
obj[keyValue[0]] = keyValue[1];
});
DefaultCat = obj["DefaultCat"];
ShortId = elements[i].children[1].alt;//New style to take ShortID
if(DefaultCat==0)setDefaultCatToProductId(parseInt(ShortId));
arrSortedOrder[i]=parseInt(ShortId);
}
Any one know how to get to this value?
p.s
Plz Do NOT give me solution with $(.spanDefCat) because when i find deff=0 i need to take ShordId as Well from this element[i]
Try this:
$(".cart-item").each(function(){
var shortId = $(this).find(".bold-14").parent("li").siblings("li").children("span").html();
var shortItem = shortId.replace(' ','').split(":");
var defaultCat = $(this).find(".spanDefCat").html();
var item = defaultCat.replace(' ','').split(":");
if(item[1]==0){
var id = parseInt(shortItem[1]);
//do something
}else{
var id = parseInt(shortItem[1]);
//do something else
}
console.log(defaultCat);
console.log(shortId);
});
Note: Above code give you the DefaultCat:334 and ShortId:1010 so now you can use both in if else statement.
If the format of DefaultCat:334 is same for all cart item then you can check whether it is 0 or not
JSFIDDLE DEMO
I see JQuery tag so i give you a response with JQuery statements.
$(".cart-item").find(".spanDefCat").each(function(index, domEle){
//get text, delete spaces and split
split_result = $(domEle).text().replace(' ','').split(":");
//get only numeric value as string
defaultCat = split_result[1];
//parse into int
defaultCat = parseInt(defaultCat);
//if your var is equal to 0
if(defaultCat == 0){
/*********************
* Type you code here *
**********************/
}
});

Categories

Resources