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);
Related
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
I am building a list automatically from a JSON with the following code
dataObject.forEach(newList);
function newList(item, index) {
var s = item.time;
alert(s);
var list = $('<li onclick="myFunction(s)">' + listItemString + '</li>');
....
}
The alert(s) print the right values of s but when I click on the element I get an error ReferenceError: s is not defined
You have to append the variable s
function newList(item, index) {
var s = item.time;
var list = $('<li onclick="myFunction(\'' + s + '\')">' + listItemString + '</li>');
....
}
You need to use
var list = $('<li>' + listItemString + '</li>');
list.on('click', function {
myFunction(s);
})
Try with:
var list = $('<li onclick="myFunction(this)">' + listItemString + '</li>');
Then you can access item.time inside myFunction
Having a tuff time figuring this out. I am building a front-end WooCommerce cart component that will add multiple products to the cart by passing the product ID into the URL. The URL structure will ultimately look like this http://cleancolor.staging.wpengine.com/?add-to-cart=2998,3339,2934 where the 2998,3339,2934 are the WooCommerce Product ID's.
Here is a live working version (without the append) http://studiorooster.com/dojo/cleancolor/ - just click on a "5 Pack" or "10 Pack" and select an addon. I have the product id's appended to the Addon name to the right side list and have the attribute named data-itemid
Here is my html block
<div class="col-md-3 clearfix" id="order_summary_box">
<div class="summary-box">
<div class="heading-total">Order Summary : <span class="color-txt" id="order_total"><span>$</span>0</span>
</div>
<div class="summary-basic-pack">
<h5>Whats in Your Bundle</h5>
<ul class="entree-add" id="entree-add">
<li id="no-entrees">No Entrees Added</li>
</ul>
<ul class="pack-add" id="pack-add">
<li id="no-addons">No Addons Selected</li>
</ul>
</div>
<div class="orderbtn-area">
<div class="order-btn-cont"><i class="fa fa-check-circle-o" aria-hidden="true"></i> Subscribe Now !</div>
</div>
</div>
</div>
jQuery
$('#get-started').delegate('.check-opt', 'click', function () {
let cost = '0';
let itemname = '';
let first = '';
let itemid = ''
if ($(this).is(':checked')) {
cost = $(this).attr('data');
itemid = $(this).attr('data-itemid');
order_additional_options += Number(cost);
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
$("#no-addons").remove();
$(".pack-add").append("<li data-cost='" + cost + "' data-id='item_" + first + cost + "' data-itemid='" + itemid + "'>" + itemname + itemid + "</li>");
} else { // minus unchecked value
cost = $(this).attr('data');
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
order_additional_options -= Number(cost);
$('[data-id=item_' + first + cost + ']').remove();
}
cart_update();
});
// on click order button submit the form
$('#order_btn_id').on("click", function () {
$('a').attr("href", "http://cleancolor.staging.wpengine.com/?add-to-cart=");
});
Determine whether the window has a push stat
Find all elements that are added to the .pack-add and extract their number
Compile a , delimited string
The following sections that starts and end with //*************
in the snip below should do the trick. Probably you can refactor it into a function.
// add and remove check box items on summary
$('#get-started').delegate('.check-opt', 'click', function () {
let cost = '0';
let itemname = '';
let first = '';
let itemid = ''
if ($(this).is(':checked')) {
cost = $(this).attr('data');
itemid = $(this).attr('data-itemid');
order_additional_options += Number(cost);
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
$("#no-addons").remove();
$(".pack-add").append("<li data-cost='" + cost + "' data-id='item_" + first + cost + "' data-itemid='" + itemid + "'>" + itemname + itemid + "</li>");
// ********************* INSERTED CODES
var all_values=""
$(".pack-add").children().each(function(){
all_values+=$(this).attr('data-itemid')+" "
})
console.log(all_values.trim().replace(" ",","));
var query_string="?add-to-cart="+all_values.trim().replace(/ /g,",");
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + query_string;
window.history.pushState({path:newurl},'',newurl);
}
// **********************END OF NEW CODES
} else { // minus unchecked value
cost = $(this).attr('data');
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
order_additional_options -= Number(cost);
$('[data-id=item_' + first + cost + ']').remove();
// ********************* INSERTED CODES
var all_values=""
$(".pack-add").children().each(function(){
all_values+=$(this).attr('data-itemid')+" "
})
console.log(all_values.trim().replace(" ",","));
var query_string="?add-to-cart="+all_values.trim().replace(/ /g,",");
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + query_string;
window.history.pushState({path:newurl},'',newurl);
}
}
cart_update();
});
trying to prepend my list in jquery mobile but I just can't get the divider to be on top of the most recent item added to the listview.
I've tried prepending the item that's being added but it then switches the divider to the bottom.
function loadScanItems(tx, rs) {
var rowOutput = "";
var $scanItems = $('#scanItems');
$scanItems.empty();
var bubbleCount = 0;
for (var i = 0; i < rs.rows.length; i++) {
bubbleCount = bubbleCount + 1;
//rowOutput += renderScan(rs.rows.item(i));
var row = rs.rows.item(i)
var now = row.added_on;
var date = get_date(now);
rowOutput += '<li data-icon="false"><div class="ui-grid-b"><div class="ui-block-a" style="width:50%"><h3>Su # ' + row.sunum + '</h3><p> Bin # ' + row.binnum + '</p></div><p class="ui-li-aside"><strong>' + date + '</strong></p><div class="ui-block-b" style="width:20%"></div><div class="ui-block-c" style="width:25%"><br><p>User: ' + row.userid + '</p></div></div></li>';
// rowOutput += '<li>' + row.sunum + row.binnum+ "<a href='javascript:void(0);' onclick='webdb.deleteScan(" + row.ID + ");'>Delete</a></li>";
}
$scanItems.append('<li data-role="list-divider">Scanned Items <span class="ui-li-count">' + bubbleCount + '</span></li>').listview('refresh');
$scanItems.append(rowOutput).listview('refresh');
}
The code is above with it correctly formatted with the divider on top but the list items being appended to the bottom instead of prepended to the top.
Thanks!
The problem is that your are building a string with all the scan items. That string already has an order so whether you prepend or append makes no difference. Try this simple change.
Change:
rowOutput += '<li data-icon="false">...</li>';
to:
rowOutput = '<li data-icon="false">...</li>' + rowOutput;
This will put your rowOutput string in the correct order before appending to the listview.
Here is a working DEMO
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++
});