I've a listview created by a loop:
for(var i = 0; i < data.length; i++) {
var garage = data[i];
$("#content-p").append(
"<ul data-role=\"listview\">" +
"<li><a href=\"#\" id=\"submitID\" >" +
"<h2>"+garage.location+"</h2>" +
"<p><b>"+garage.description+"</b></p>" +
"<p>"+garage.address+"</p>" +
"</a></li>" +
"</ul><br>"
);
$("#submitID").click(function() {
localStorage.setItem("garageID",garage.ID);
$.mobile.changePage("#resP");
});
}
Now the user can click on a listview item and the ID from this item should be stored in the localStorage.
Problem: It first creates the complete listview with all items. If I click now on item#2 from the list, I get the ID from the last item.
the submit function is being overwritten with every iteration of the loop, and every single #submitID is only calling that function. So, of course it will only pull up the last one in the list.
Also, the code is generating all items within data.length, so you'll need to alter that if you don't want everything in the list.
Here's a fix to the first part (assuming no styling is assigned to #submitID):
for(var i = 0; i < data.length; i++) {
var garage = data[i];
$("#content-p").append(
"<ul data-role=\"listview\">" +
"<li><a href=\"#\" id=\"submitID-" + i + "\" >" +
"<h2>"+garage.location+"</h2>" +
"<p><b>"+garage.description+"</b></p>" +
"<p>"+garage.address+"</p>" +
"</a></li>" +
"</ul><br>"
);
$("#submitID-" + i).click(function() {
localStorage.setItem("garageID",garage.ID);
$.mobile.changePage("#resP");
});
}
I think the problem was that the method was trying to reference garage when there wasn't a reference, or something like that. And you should have made the click method for a specific ID, because it just kept getting overridden each time. I fixed it for you by making it one click method for a class, but the ID of each garage element is its actual garage ID.
http://jsfiddle.net/Fq3TF/1/
Also, just a tip, if you're constructing a string which is going to be inserted into an HTML document, you can use an apostrophe instead of a quote to avoid escaping. e.g. "<a class='submitID'>Hello World</a>".
Here is my take on the problem. I use a attribute to save the id in the a element. The registering of the click handler has been moved outside the loop.
var data = [
{
id: "id1",
location: "location1",
description: "description1",
address: "address1"
},
{
id: "id2",
location: "location2",
description: "description2",
address: "address2"
}
];
for (var i = 0; i < data.length; i++) {
var garage = data[i];
$("#content-p").append(
"<ul data-role=\"listview\">" +
"<li><a href=\"#\" class=\"submitClass\" garageid=\"" + garage.id + "\">" +
"<h2>" + garage.location + "</h2>" +
"<p><b>" + garage.description + "</b></p>" +
"<p>" + garage.address + "</p>" +
"</a></li>" +
"</ul><br>"
);
}
$(".submitClass").click(function(e) {
e.stopPropagation();
alert($(this).attr("garageid"));
/*localStorage.setItem("garageID", garage.ID);
$.mobile.changePage("#resP");*/
});
Related
I wrote this code and it works:
function getJsonResult(retrieve) {
var result = retrieve.results;
for (var i = 0; i < result.length; i++) {
responseJson.push({ id: result[i].id, title: result[i].title });
var search = '<a id="' + result[i].id + '">' + result[i].title + '</a><br/>';
document.write(search);
}
}
When I tried to display the results in a div, I change the last line with:
$("#divId").html(search);
But it only displays the first result. How can I make the whole list appear?
That happened because you're overriding the search variable in every iteration :
var search = '<a id="' + result[i].id + '">' + result[i].title + '</a><br/>';
You need to declare the search variable outside of the loop then append the string in every iteration like :
function getJsonResult(retrieve) {
var result = retrieve.results;
var search = "";
___________^^^^
for (var i = 0; i < result.length; i++) {
responseJson.push({ id: result[i].id, title: result[i].title });
var search += '<a id="' + result[i].id + '">' + result[i].title + '</a><br/>';
___________^^
document.write(search);
}
}
Then finally you could put your variable content to the div :
$("#divId").html(search);
$('#divId').append(search);
This appends the element included in search to the div element.
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 am trying to generate divs around each of the elements of a two dimensional array using the methods below. So far the code only outputs the last 3 elements in the array (the 3 elements of third nested array). I am passing the array elements as parameters using .apply. How could I modify this to output each element of the array catArray in order? And why would it only pass the last 3 as it is? Any advice would be appreciated, I am trying to understand this better. I have spent hours on this, hopefully someone can help.
Here is a codepen:
http://codepen.io/anon/pen/kzEdK
function cats(catName, catFur, catEyes) {
$("#row").html('<div>' + catName + '</div>' + '<div>' + catFur + '</div>' + '<div>' + catEyes + '</div>');
}
var catArray = [
["fluffy", "soft", "green"],
["mittens", "coarse", "fire"],
["wiskers", "none", "grey"]
];
function catGenerator() {
for (var i = 0; i < catArray.length; i++) {
var blah = catArray[i];
cats.apply(this, blah);
}
}
catGenerator();
You probably want something like:
function cats(catName, catFur, catEyes) {
// note the difference (append() instead of html())
$("#row").append('<div>' + catName + '</div>' + '<div>' + catFur + '</div>' + '<div>' + catEyes + '</div>');
}
function catGenerator() {
$("#row").html(""); // in case you wish to call catGenerator() multiple times, clear the row before appending to it
for (var i = 0; i < catArray.length; i++) {
var blah = catArray[i];
cats.apply(this, blah);
}
}
It shows only the last 3 elements because $("#row").html("...") overwrites the contents of #row three times and the value set in the last iteration remains visible. I fixed that by replacing html() with append(), which does what you want.
The problem is that you have $("#row").html() which will replace the markup within the div tag after each iteration. Consider using $("#row").append()
function cats(catName, catFur, catEyes) {
$("#row").append('<div>' + catName + '</div>' + '<div>' + catFur + '</div>' + '<div>' + catEyes + '</div>');
}
var catArray = [
["fluffy", "soft", "green"],
["mittens", "coarse", "fire"],
["wiskers", "none", "grey"]
];
function catGenerator() {
for (var i = 0; i < catArray.length; i++) {
var blah = catArray[i];
cats.apply(this, blah);
}
}
catGenerator();
Should be very simple, but I only get Jimmy cricket output and I'm expecting all the names in li tags. Thanks for any help.
<ul id="members"></ul>
<script>
var teammembers = [
{"name":"John Doe", "profile":"/img/profile/user1.jpg", "position":"President", "email":"email#example.com", "phone":"242-abcd"},
{"name":"James Bond", "profile":"/img/profile/user2.jpg", "position":"Vice President", "email":"007#example.com", "phone":"242-0007"},
{"name":"Jimmy Cricket", "profile":"/img/profile/user3.jpg", "position":"Vice Cricket", "email":"cricket#example.com", "phone":"242-wxyz"}
];
for (var i = 0; i < teammembers.length; i++) {
document.getElementById("members").innerHTML = "<li>" + teammembers[i].name; + "</li>"
}
</script>
The = sign here is replacing the innerHTML on each iteration. Hence you see the last value of the array here.
Convert it to a +=. Like this,
document.getElementById("members").innerHTML += "<li>" + teammembers[i].name; + "</li>"
+= will append it.
You need to append to the innerHTML, rather than set it. Instead of this:
document.getElementById("members").innerHTML = "<li>" + teammembers[i].name; + "</li>"
use this (the change is from using = to using +=):
document.getElementById("members").innerHTML += "<li>" + teammembers[i].name; + "</li>"
So i have a page that has a couple of jQuery plugins. Among other things i have the multiselect toolbar, a pretty sweet plugin. problem is that when i load up the page in internet explorer the page breaks. i've been able to determine that the problem occurs when i try to set some attributes to some elements that i have dynamically generated.
here is the code for generating the elements:
$.ajax({
url: '#Url.Content("~")' + 'Ticket/GetTvrtke',
async: false,
success: function (data) {
document.getElementById("header_tvrtka_holder").innerHTML = data;
var tvrtke = data.split(", ");
for (var i = 0; i < tvrtke.length; i++) {
document.getElementById("KlijentMultiSelect").innerHTML +=
"<option value=\"" + tvrtke[i] + "\" id=\"" + tvrtke[i] + "\" >" + tvrtke[i] + "</option>";
}
$("#KlijentMultiSelect").multiselect({
selectedText: "",
height: 125,
minWidth: 650,
noneSelectedText: 'Izaberite željene tvrtke:'
});
}
});
the function gets the correct data and generates the options, and then i activate the plugin to render the new dropdown menu with checkboxes.
problem is that afterwards i have this code:
var tvrtke = document.getElementById("header_tvrtka_holder").innerHTML.split(", ");
for (var i = 0; i < tvrtke.length; i++) {
document.getElementById("ui-multiselect-" + tvrtke[i]).checked = true;
}
for (var i = 0; i < tvrtke.length; i++) {
document.getElementById("ui-multiselect-" + tvrtke[i]).setAttribute("onclick", "ChangeTextKlijent()");
}
here i am trying to set the checkbox values to true and add an on click event to the input element, but then visual studio sends me the error message from the title. in firefox, everything works great but IE is a whole different story.
anyone know how to fix this?
I switched so that my code looks like this:
var tvrtke = document.getElementById("header_tvrtka_holder").innerHTML.split(", ");
$.each(tvrtke, function (index, value) {
$("#KlijentMultiSelect").append("<option value=\"" + value + "\" id=\"" + value + "\" >" + value + "</option>");
});
and now it works.