Working with the Google maps and places API, I am rendering infowindows for each marker that gets generated by a function generateInfoWindow(location).
In there I create a string HTML that will be passed to the Google maps markers content attribute.
Function
function generateInfoWindow(location) {
var html = "<div class = 'infowindowContainer'>" +
"<span class = 'infoWindowHeader'>" + location.name + "</span>" +
"<div class = 'row'>" +
"<span class = 'col-xs-12'> ... : " + getInfoWindowDetails(location).adress + "</span>" +
"<span class = 'col-xs-12'> ... : " + getInfoWindowDetails(location).open_hours + "</span>";
if (location.offers.length > 0) {
html +=
"<span class = 'col-xs-12 iwOffers'> ... </span>" +
"</div>" + //ends row
"<div class = 'infoWindowCircleContainer'>";
for (var i = 0; i < location.offers.length; i++) {
html += "<span class = 'infoWindowCircle'>" + location.offers[i].offer_text + "</span>";
}
html += "</div>" //CircleContainer
}
html += "<span class = 'showMore' onclick = 'processWin(" + location + ")'>Show more</span>";
html += "</div>"; //InfoWindowContainer the parent to all
return html;
}
function processWin(location) {
var winMarker;
var winnerMap;
var mapOptions = {
zoom: 15,
center: location.geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: googleMapsStyles
};
var locationId = location.place_id;
var request = {
placeId: locationId
};
places.getDetails(request, getWinnerDetails); //Where getWinnerDetails is the callback
//since the location that we are passing in the callback function is the one we get as a JSON from the detailed search we are going to have to use our modified vars associated with the location here such as .keyword
$("#foodType").text("Typ av mat : " + location.keyword);
winnerMap = new google.maps.Map(document.getElementById('displayWinnerMap'), mapOptions);
for (var i = 0; i < markers.length; i++) {
if (markers[i].placeId == location.place_id) {
winMarker = markers[i];
break;
}
}
//setOfferCircles(location);
winMarker.setMap(winnerMap);
$("#displayWinPage").css("display", "block");
doScroll("#displayWinPage");
}
Where I append the span with the class showMore I wish to append an onclick event that will call a method processWin(location) where I pass the location variable. (Will be multiple markers).
I can't seem to be able to pass the object location in the onclick event and
I don't understand why. Please do enlighten me.
An object converted to a string becomes [object object] and that is what you are passing as the parameter and not the object itself. Here is example code showing the wrong output
var location = {x : 100, y : 100};
var html = "<span class = 'showMore' onclick = 'processWin(" + location + ")'>Show more</span>";
console.log(html);
Output: <span class = 'showMore' onclick = 'processWin([object Object])'>Show more</span>
Using JSON.stringify(location) you get the object output correctly as shown below.
var location = {x : 100, y : 100};
var html = "<span class = 'showMore' onclick = 'processWin(" + JSON.stringify(location) + ")'>Show more</span>";
console.log(html);
Output:<span class = 'showMore' onclick = 'processWin({"x":100,"y":100})'>Show more</span>
Related
I am using MapBox to render a map. I have made a onClick function wherein when clicked on the map it shows the geocode information shown in the screenshot below through api.
Now what I want is to have a button below the table and when click on it I want it to execute a particular function, I have defined it but when clicked on it says Function is not defined
Code
map.current.on('click', function(e) {
var coordinates = e.lngLat;
var lng = coordinates.lng;
var lat = coordinates.lat;
console.log(lat);
console.log(lng);
var d = fetch("https://api.mapbox.com/geocoding/v5/mapbox.places/" + lng + "," + lat + ".json?access_token={token_value}").then(response => response.json()).then(function(data) {
console.log(data)
var str = "<table border='1'><tr><td><center>Title</center></td><td><center>Content</center></td></tr>"
for (let i in data["features"]) {
str = str + "<tr><td style='padding:5px'>" + data["features"][i]["place_type"][0] + "</td><td style='padding:5px'>" + data["features"][i]["place_name"] + "</td></tr>"
}
str = str + "</table>"
// button
str = str + "<button onClick={myFunction}>Save</button>"
function myFunction() {
console.log('Saved pressed');
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(str)
.addTo(map.current)
});
console.log(d);
});
Fix code as below
// button
str += `<button onclick="myFunction()"}>Save</button>`;
I would guess the button (and the function name defined for it) are created with a different scope than where you have defined your function. One of these might work:
Define your function as const myFunction = () => console.log("saved pressed").
Try referencing your function as this.myFunction
I am trying to allow clients to create a list of students then view more info by simply clicking on the button with the students name. I've got it to create the button and display the students name in the button but it only calls the function when I click submit to add the student to the list, the actual student button doesn't seem to function.
function updateStudentList() {
var html = "";
for (var i = 0; i < students.length; i++) {
html += "<li><button type='button' class='studentButton'" + "id=" + students[i].name +">" + students[i].name + "</button></li>";
}
$('#studentList').html(html);
for (var i = 0; i < students.length; i++) {
document.getElementById(students[i].name).addEventListener('click', openStudentInfo(students[i].name));
}
}
function openStudentInfo(studentName) {
console.log("Opening " + studentName + " info.");
var studentInfo = requestStudentByName(studentName);
if (studentInfo != null) {
var studentInfoForm = $("#studentInfoForm");
var html = "";
html += "<h3>Student Name: " + studentInfo.name + "</h3>";
html += "<h3>Student ID: " + studentInfo.studentID + "</h3>";
studentInfoForm.html(html);
$("#studentInfoModal").show();
}
}
HTML:
<ul data-role="listview" id="studentList"> </ul>
Note: I can't use the onclick tag in HTML, it causes security issues. Cordova also blocks this.
The way you binding the event is not ok. Try binding this way:
$(document).ready(function() {
$("#studentList").on("click", ".studentButton", function() {
var studentId = $(this).data("studentid");
openStudentInfo(studentId);
});
});
And in your HTML generation:
html += "<li><button type='button' class='studentButton' data-studentid='" + students[i].studentID +"'>" + students[i].name + "</button></li>";
This kind of event delagation works not metter how you create the elements inside the root element(studentList in this case), because the event was bound in it, and not on the dynamic elements.
no jquery version of DontVoteMeDown's answer
document.getElementById('studentList').addEventListener('click', function(event) {
var clickedEl = event.target;
if(clickedEl.className === 'studentButton') {
var studentId = clickedEl.dataset.studentId;
openStudentInfo(studentId);
}
});
I have a JavaScript function that loops through classes and gets an ID which I have wrapped in a div called 'item'. Once they click on a button it bubbles up through the div which I have wrapped information in and collected the ID. For Example:
output = "<div id='item" + json_output[i].id + "'>" +
"<div class = 'itemBoxes'>"+
"<h3 class ='itemTitle'>" +json_output[i].classname + "</h3>" +
"<div class = 'paddingBottom'></div>" +
"<p class = 'itemDesc'>" + json_output[i].classdescription + '</p>' +
"<div class ='itemInfo'>" +
"<div class ='bookingItems'> <img src = 'img/glyphicons-268-credit-card.png'</img> <p class = 'itemDetails'>£" + json_output[i].classprice + "</p></div> "+
"<div class ='bookingItems'> <img src = 'img/glyphicons-46-calendar.png'</img> <p class = 'itemDetails'>" + json_output[i].classdate + "</p></div>" +
"<div class ='bookingItems'> <img src = 'img/glyphicons-55-clock.png'</img><p class = 'itemDetails'>"+ json_output[i].classstarttime +"</p></div>" +
"<div class ='bookingItems'> <img src = 'img/glyphicons-44-group.png'</img><p class = 'itemDetails'>" + json_output[i].classparticipants + " spaces </p></div>" +
"</div>" +
"<p id ='bookingBox'> <input type='button' class='bookingSubmit' value='Book Now'/> </p>" +
"</div>" +
"</div>";
target.innerHTML += output;
The code I use to find the ID is:
var fetchModifyButton;
//Gets the button that says 'Modify'
fetchModifyButton = _c("bookingSubmit");
//Remove Button.
for (var i = 0, j = fetchModifyButton.length; i < j; i++) {
fetchModifyButton[i].addEventListener("click", function () {
var e, productID, newID;
//Bubbles up and finds the ID of the product they want to modify
e = event.target;
while (e.id.indexOf('item') == -1) {
e = e.parentNode;
}
productID = e.id;
//Removes everything but the numbers.
newID = productID.replace(/[^0-9.]/g, "");
getClassInfoForBooking(newID, newID);
});
}
This works perfectly in Google Chrome, IE11, and most other browsers.
It doesn't work in IE8,9 or 10.
The error message I get in is:
SCRIPT5007: Unable to get property 'id' of undefinded or null reference
Then it points to the line: while (e.id.indexOf('item') == -1) {
I wondered if anyone had any ideas why?
use event.srcElement for IE
var addEvent = window.addEventListener||window.attachEvent;
fetchModifyButton[i].addEvent("click", function () {
var e, productID, newID;
//Bubbles up and finds the ID of the product they want to modify
e = event.target||event.srcElement;
while (e.id.indexOf('item') == -1) {
e = e.parentNode;
}
productID = e.id;
//Removes everything but the numbers.
newID = productID.replace(/[^0-9.]/g, "");
getClassInfoForBooking(newID, newID);
});
Here's my code for gathering titles/posts from reddit's api:
$.getJSON("http://www.reddit.com/search.json?q=" + query + "&sort=" + val + "&t=" + time, function (data) {
var i = 0
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
i++
});
});
Basically every post (selftext) is assigned a different paragraph id (post0, post1, post2, etc) for every result that's pulled. I'm also going to create a "hide" button that follows the same id scheme based on my i variable (submit0, submit1, submit2, etc). I want to write a function so that based on which button they click, it will hide the corresponding paragraph. I've tried doing an if statement that's like if("#hide" + i) is clicked, then hide the corresponding paragraph, but obviously that + i doesn't work. How else can I tackle this?
Could you try something like the below?
showhide = $("<a class='hider'>Show/Hide</a>");
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
}
Alternatively:
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var showhide = $("<a class='hider" + i + "'>Show/Hide</a>");
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
});
i++
});
Today , i have been read all the topic about this but couldn't come up with a solution that's why i am opening this topic.
This is my function which creates the view and i am trying to have a onclick function which should directs to other javascript function where i change the textbox value.
<script type="text/javascript">
$('#submitbtnamazon')
.click(function(evt) {
var x = document.getElementById("term").value;
if (x == null || x == "" || x == "Enter Search Term") {
alert("Please, Enter The Search Term");
return false;
}
listItems = $('#trackList').find('ul').remove();
var searchTerm = $("#term").val();
var url = "clientid=Shazam&field-keywords="
+ searchTerm
+ "&type=TRACK&pagenumber=1&ie=UTF8";
jsRoutes.controllers.AmazonSearchController.amazonSearch(url)
.ajax({
success : function(xml) {
$('#trackList')
.append('<ul data-role="listview"></ul>');
listItems = $('#trackList').find('ul');
html = ''
tracks = xml.getElementsByTagName("track");
for(var i = 0; i < tracks.length; i++) {
var track = tracks[i];
var titles = track.getElementsByTagName("title");
var artists = track.getElementsByTagName("creator");
var albums = track.getElementsByTagName("album");
var images = track.getElementsByTagName("image");
var metaNodes = track.getElementsByTagName("meta");
//trackId ="not found";
trackIds = [];
for (var x = 0; x < metaNodes.length; x++) {
var name = metaNodes[x]
.getAttribute("rel");
if (name == "http://www.amazon.com/dmusic/ASIN") {
trackId = metaNodes[x].textContent;
trackIds.push(trackId);
}
}
for (var j = 0; j < titles.length; j++) {
var trackId=trackIds[j];
html += '<div class="span3">'
html += '<img src="' + images[j].childNodes[0].nodeValue + '"/>';
html += '<h6><a href="#" onclick="someFunction('
+trackId
+ ')">'
+trackId
+ '</a></h6>';
html += '<p><Strong>From Album:</strong>'
+ albums[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Artist Name:</strong>'
+ artists[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Title:</strong>'
+ titles[j].childNodes[0].nodeValue
+ '</p>';
/*html += '<p><Strong>Created:</strong>'
+ releaseDate
+ '</p>';*/
html += '</div>'
}
}
//listItems.append( html );
$("#track").html(html);
$("#track").dialog({
height : 'auto',
width : 'auto',
title : "Search Results"
});
// Need to refresh list after AJAX call
$('#trackList ul').listview(
"refresh");
}
});
});
</script>
This is my other function where i change the textbox value. it works actually with other values e.g. when i give hardcoded string value. I can see the value in the console but for some reason it gives me the error like :
here the string starts with B is AsinId where i take from amazon. I am definitely in need of help because i am totally stucked.
Uncaught ReferenceError: B00BMQRILU is not defined 62594001:1 onclick
<script type="text/javascript">
function someFunction(var1) {
tracktextbox = document.getElementsByName("trackId");
for (var i = 0; i < tracktextbox.length; i++) {
tracktextbox[i].value = var1;
}
$('#track').dialog('close');
}
</script>
The problem is '<h6><a href="#" onclick="someFunction('+trackId+ ')">', from the error it is clear that trackId is a string value, so you need to enclose it within "" or ''. So try
'<h6><a href="#" onclick="someFunction(\'' + trackId + '\')">'