HTML.
<div id="listsalon">
<ul data-role="listview" data-inset="true" data-filter="true" >
</ul>
</div>
JS.
for (var i = 0; i < arr.length; i++) {
companyname = arr[i].CompanyName;
picture = arr[i].Picture;
address = arr[i].Address;
$("#listsalon ul").append("<li class='ui-corner-all'>" +
"<a id=" + '"' + "salon" + (i + 1) + '"' + "><img src='" + picture +
"'style='height:160px; width:200px;' class='ui-corner-all'>" +
"<h2 style='font-size:13px'>" + companyname + "</h2>" +
"<p style='font-size:10px'>" + address + "</p>" +
"</a></li>");
}
$("#salon1").bind("click", function () {
window.location = "salon.html"
});
Problem:
So first I pull data and put in 3 variables, companyname, picture and address. i have x sets of these data. i want to put in a list form. i am able to list out, but the function doesn't recognise the id and it does not work. please help. ty
This is because #salon1 element is being created dynamically. Moreover, .bind() in JQuery is deprecated. For such cases you should use .on()
$("#listsalon").on("click", "a#salon1", function () {
window.location = "salon.html"
});
More at jQuery click not working for dynamically created items
Proof of work
var arr = [{"CompanyName": "A", "Picture": "https://via.placeholder.com/140x100", "Address": 1}, {"CompanyName": "B", "Picture": "https://via.placeholder.com/140x100", "Address": 2}];
for (var i = 0; i < arr.length; i++) {
var companyname = arr[i].CompanyName;
var picture = arr[i].Picture;
var address = arr[i].Address;
$("#listsalon ul").append("<li class='ui-corner-all'>" +
"<a href='#' id=" + '"' + "salon" + (i + 1) + '"' + "><img src='" + picture +
"'style='height:160px; width:200px;' class='ui-corner-all'>" +
"<h2 style='font-size:13px'>" + companyname + "</h2>" +
"<p style='font-size:10px'>" + address + "</p>" +
"</a></li>");
$("#listsalon").on("click", "a#salon"+(i+1), function () {
alert("Redirecting...");
window.location = "salon.html"
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="listsalon">
<ul data-role="listview" data-inset="true" data-filter="true" ></ul>
</div>
To add event listeners to dynamically created objects, you need to create DOM objects using document.createElement. This lets you hold to the actual element even before appending it.
Then, you can use it like you would use any other object retrieved using a query string.
$(document).ready(function() {
let array = ["a", "b", "c"];
for (let i = 0; i < array.length; i++) {
let el = document.createElement('li');
$(el).html(array[i]);
$(el).on('click', function() {
alert('Click!');
});
$("#listsalon ul").append(el);
}
});
#listsalon ul li {
background-color: #eee;
padding: 0.5em;
margin-bottom: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="listsalon">
<ul data-role="listview" data-inset="true" data-filter="true" >
</ul>
</div>
CSS styles are just for clarity.
Here is a sample. .bind() in JQuery is deprecated. For such cases, you should use .on()
for (var i = 0; i < 5; i++) {
$("#listsalon ul").append("<li class='ui-corner-all'>" +
"<a id=" + '"' + "salon" + (i + 1) + '"' + ">"+(i + 1)+"</a></li>");
$("#salon"+(i + 1)).on("click", function () {
alert('clicked')
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="listsalon">
<ul>
</ul>
</div>
You were defining your click function outside for loop. That's why DOM didn't recognize your id
Related
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 append html to a Content Holder in a dialogue box and as you can see by the image, Mile, Meter and Kilometer are outside the select dropdown. Why is this?
var rows = $('#jqxUOMRelatedUnitsDropdownGrid').jqxGrid('getrows');
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").html('<select id="listNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder">');
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.UOMRelatedUnit_AddItem) {
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append("<option value='" + row.UOMRelatedUnit_Name + "'>" + row.UOMRelatedUnit_Name + "</option>");
}
}
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append("</select>");
<div id="divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder"></div>
Because you are appending into the <div> and not the <select>. Do this way:
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder select").append("<option value='" + row.UOMRelatedUnit_Name + "'>" + row.UOMRelatedUnit_Name + "</option>");
// --------------------------------------------------- ^^^^^^
And you cannot do:
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append("</select>");
That's invalid! Either store everything in a tempAppend string and then use:
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append(tempAppend);
I'm getting an unexpected identifier error in chrome for the last line of this code, does anyone know why? thanks (updated to entire code for the page)
It's supposed to display a list of data for the jobs ive got entered into a database
<?php
error_reporting(0);
include('../includes/header.php');
include('connection.php');
?>
<script src="../jqm/demos/js/jquery.js"></script>
<script type="text/javascript">
var db;
$(document).ready(function () {
loadJobRecords();
}
$(document).on("click", "#jobRecord", function () {
getJobById($(this).data("key"));
});
});
function loadJobRecords() {
db.transaction(function (txs) {
txs.executeSql('SELECT * FROM jobs', [], function (txs, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
var JobRecord = results.rows.item(i);
var individualJob = '';
individualJob = '<li><a href="#detailinfo" id="jobRecord" data-key="' + jobRecord.ID + '" >';
individualJob += '<h3>' + jobRecord.Title + '</h3>';
individualJob += '<p>Testing</p>';
individualJob += '</a></li>';
$('#listofjobs ul').append(individualJob);
$('#listofjobs ul:visible').listview('refresh');
}
});
});
}
function getJobById(id) {
db.transaction(function (txs) {
txs.executeSql('SELECT * FROM jobs WHERE id="' + ID + '"', [], function (txs, results) '){
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
var jobRecord = results.rows.item(i);
var individualjob = '';
individualjob += '<h3>' + jobRecord.Title + '</h3>';
individualjob += '<p>' + jobRecord.Description + '</p>';
individualjob += '<p>' + jobRecord.Username + '</p>';
$('#jobSummary').html(individualJob);
}
});
});
}
</script>
<div class="content container">
<div daa-role="page" id="jobsdatabase">
<section>
<div data-role="content" id="listofjobs">
<ul data-role="listview" data-filter="true" data-inset="true">
</ul>
</section>
</div>
</div>
</div>
<?php include('../includes/footer.php'); ?>
Maybe the jquery selector doesn't find a match?
Try going to the console in chrome and running:
$('#listofjobs ul:visible').length
Is the value greater than 0?
Change to this
var db;
$(document).ready(function () {
loadJobRecords();
$(document).on("click", "#jobRecord", function () {
getJobById($(this).data("key"));
});
});
function loadJobRecords() { ...
You have a quote ' and bracket at the end of this line, just after results - remove them
txs.executeSql('SELECT * FROM jobs WHERE id="' + ID + '"', [], function (txs, results) '){
change to
txs.executeSql('SELECT * FROM jobs WHERE id="' + ID + '"', [], function (txs, results){
So I'm trying to append a new <li> and increase its ID number by 1 every time so I end up having something like:
<ul id="bxs">
<li id="item-1">1</li>
<li id="item-2">2</li>
<li id="item-3">3</li>
<li id="item-4">4</li>
<li id="item-5">5</li>
<li id="item-6">6</li>
</ul>
This is what my jQuery looks like:
var itemCount = 1;
$(function() {
$("#NewItem").click(function(e) { // NewItem is my button
e.preventDefault();
itemCount++;
var element = $("<li id="item-" + itemCount>" + itemCount + "</li>");
$("#bxs").append(element);
});
});
What I'm I doing wrong? There must be something wrong on where I add the itemCount in the div. I tried this as well: <li id="item-" + itemCount + "> but doesn't work either.
Can someone guide me please?
Your not concatenating your string properly. You should be using single quotes inside your double quotes. In addition, you can't set itemCount = 1 if you already have existing items. I suggest setting itemCount dynamically. See example below (and fiddle).
$(function() {
$("#NewItem").click(function(e) { // NewItem is my button
e.preventDefault();
var itemCount = ($("[id^='item-']").length + 1);
var element = $("<li id='item-" + itemCount + "'>" + itemCount + "</li>");
$("#bxs").append(element);
});
});
Here's a working fiddle.
try this...
var element = $("<li id='item-" + itemCount +"'>" + itemCount + "</li>");
That is a a weird string, try using single quotes fro your string instead;
var element = $('<li id="item-' + itemCount + '">' + itemCount + '</li>');
Why are you using $( in front of the HTML code?
var element = '<li id="item-' + itemCount+ '">' + itemCount + '</li>';
Think this does the trick
var element = $("<li id="item-" + itemCount>" + itemCount + "</li>");
needs to be
var element = '<li id="item-' + itemCount + '">' + itemCount + '</li>';
I always opt to use the API when possible. It saves issues like this.
var element = $("<li></li>", { id: "item-" + itemCount }).html(itemCount);
Can anyone help me with why this JavaScript is not writing to the definition list in the body? When I debug, the object is there and the lines are all executed. Also, if I use document.write the information will overwrite the page. I'm just having trouble with adding this HTML to the predefined definition list. There are no errors in the console. Any help is appreciated.
Javascript in head
function writeGph(obj, chartNum) {
var data = obj;
for (i = 0; i < obj.tab1.length; i++) { //Loop to create each column of the graph
document.getElementById(chartNum).innerhtml += '<dt>' + data.tab1[i].name + '</dt>'
document.getElementById(chartNum).innerhtml += '<dd class="p100"><span><b>' + data.tab1[i].top + '</b></span></dd>'
document.getElementById(chartNum).innerhtml += '<dd class="sub p' + data.tab1[i].bot + '"><span><b>' + data.tab1[i].bot + '</b></span></dd>';
console.log(data.tab1[i].top);
}
}
function writeAxis(obj, axisNum) {
for (i = 0; i < obj.tab1.length; i++) { //Loop to create each x-axis label
document.getElementById(axisNum).innerhtml += '<li>' + obj.tab1[i].name + '</li>';
}
}
function writeTable(obj, tableNum) {
document.getElementById(tableNum).innerhtml += '<tr><th>Business</th><th>Number</th><th>Percent</th></tr>';
for (i = 0; i < obj.tab1.length; i++) { //Loop to fill in table information
obj.tab1[i].botl = Math.round(10000 * (obj.tab1[i].num / obj.tab1[i].all)) / 100;
document.getElementById(tableNum).innerhtml += '<tr><td>' + obj.tab1[i].name + '</td><td>' + obj.tab1[i].num + '</td><td>' + obj.tab1[i].botl + '%</td></tr>';
}
}
HTML in body
<dl class="chart" id="chart1"></dl>
<ul class="xAxis" id="xAxis1"></ul>
<table id="table1"></table>
It's not .innerhtml, it's .innerHTML