JQuery mobile dynamic split button list view - javascript

I'm new in jquery mobile. I'm trying to do a dynamic split button list view.
The first button is working fine that means when it is clicked, the item list name is passed to the "gotoQuantity(this)" function. However, the second button is not working. That is the list view name is not being passed to "deleteItemFromList(this)" function.
Please how can I solve this problem?
Html:
<ul data-role="listview" data-filter="true" data-input="#myFilter" data-autodividers="true" data-inset="true" id = itemsList data-split-icon="delete">
</ul>
Script:
function loadMainList() {
//loads main items list
$("#itemsList").empty();
for (var key in mainList) {
itemToList = key;
$('#itemsList').append('<li><a onclick="gotoQuantity(this)">' + itemToList + '</a><a onclick="deleteItemFromList(this)">' + itemToList + '</a></li>');
};
$("#itemsList").listview('refresh');
}
function gotoQuantity(obj) {
alert($(obj).text());
}
function deleteItemFromList(obj) { //deletes item from main list
alert($("#itemsList").text());
}

When jQuery Mobile enhances the list, the split button text is removed and then added as the title attribute of the anchor. So your quick fix would be
function deleteItemFromList(obj) { //deletes item from main list
alert($(obj).prop('title'));
}
However, i would take SGA's approach from the comments and make the item id a data attribute of the LI and then use event delegation to create the handlers and retrieve the id:
$("#itemsList").empty();
for (var i=0; i<mainList.length; i++) {
itemToList = mainList[i];
$('#itemsList').append('<li data-id="' + itemToList + '">' + itemToList + '' + itemToList + '</li>');
};
$("#itemsList").listview('refresh');
$("#itemsList").on("click", ".goQuant", function(){
alert($(this).parent("li").jqmData("id"));
});
$("#itemsList").on("click", ".deleteItem", function(){
alert($(this).parent("li").jqmData("id"));
});
DEMO

Related

Vanilla JS category selector .removeAttribute problem

New on dev and JS following a (apparently) simple tutorial I got stacked in a silly problem, a function that has to select categories just adding or removing attributes.
It adds (and hides) but doesn't remove (and lets appear).
Function:
var showAndHideSongs = function(event, filter) {
// get all songs that match the genre of the filter
var songsByGenre = Array.from(
document.querySelectorAll('#playlist [data-genre="' + filter + '"]')
);
// if checkbox is checked, show songs
// otherwise, hide them
if (event.target.cheched) {
songsByGenre.forEach(function(song) {
song.removeAttribute("hidden");
});
} else {
songsByGenre.forEach(function(song) {
song.setAttribute("hidden", "true");
});
}
};
HTML:
<ol id="playlist">
<li data-genre="pop">
"Thank U, Next" by Arianna Grande
</li>
<li....
Checkboxes are dynamically created:
var renderCheckLists = function(genres) {
app.innerHTML =
"<h2>Filter Songs</h2><h3>By Genre</h3>" +
genres
.map(function(genre) {
var html =
"<label>" +
'<input type="checkbox" checked data-filter="' +
genre +
'" checked>' +
genre +
"</label>";
return html;
})
I tried literally everything but the solution
As I said it removes but looks like if "removeAttibute" doesn't work.
I tried the removeAttribute in a blank test project and actually works perfectly, so the problem is not there
Thanks in advance for the help

Adding onclick event on dynamically created HTML caused an error: Uncaught SyntaxError: Unexpected identifier

I'm using ajax to get an results from code behind, when I Get those results I'm creating an a divs. And this works fine, adding a div dynamically.
Now I Want to add on each div onclick event which should raise some method when it's clicked, so here is my full code:
<script>
function onSelectGroup(Id) {
$.ajax({
method: "GET",
url: "Product/GetProductsByGroupId",
data: { groupId: Id }
})
.done(function (response) {
$(".products").html("");
for (var i = 0; i < response.length; i++) {
//I wrote onclick = "addProduct(response[i])" to generate for each div each onclick event
let item = '<div class="col-md-3"> <div class="Product-holder" onclick="addProduct(' + response[i] + ')" id=' + response[i].ProductId + '><img class="img-responsive" src="images/maxresdefault.jpg"><p class="product-title" style="color:white;margin-top:5px;text-align:center;"> ' + response[i].Title + '</p></div></div>';
//Trying to append it to my .product class because it's parent of this divs above
$(".products").append(item);
}})};
function addProduct(product) {
console.log(product.Title);
}
</script>
But when I click on any of my generated divs I get an following error:
Uncaught SyntaxError: Unexpected identifier
I'm looking for issue for 3h allready, and I'm really stucked here..
Any kind of help would be great.
Thanks
P.S
CODE BEHIND - C # METHOD:
public ActionResult GetProductsByGroupId(int groupId)
{
var products = ProductController.GetProductsByGroupId(groupId);
if(products)
{
List<Product> productlist = new List<Product>();
foreach (var item in products)
{
Product product = new Product();
product.ProductId = Convert.ToInt32(item.Id);
product.Price = Convert.ToDecimal(item.Price);
product.Title = item.Title;
productlist.Add(product);
}
return Json(productlist, JsonRequestBehavior.AllowGet);
}
return Json(products, JsonRequestBehavior.AllowGet);
}
Remove the onclick and use delegate, you are passing an object to a function which convert response[i] to text [Object object], use data-* attributes to hold data for each object and attach an event to the div with the class product, on click of the div we'll use $(this) to reference the current clicked div and access its data attributes.
$(".products").html("");
var response = [{ProductId:4, Title:"Doe", Price: 34.89}, {ProductId:6, Title:"Jane", Price: 20.99}];
for (var i = 0; i < response.length; i++) {
//I wrote onclick = "addProduct(response[i])" to generate for each div each onclick event
let item = '<div class="col-md-3"> <div class="Product-holder product" data-price="'+ response[i].Price +'" data-title="' + response[i].Title + '" id=' + response[i].ProductId + '><img class="img-responsive" src="images/maxresdefault.jpg"><p class="product-title" style="color:white;margin-top:5px;text-align:center;"> ' + response[i].Title + '</p></div></div>';
//Trying to append it to my .product class because it's parent of this divs above
$(".products").append(item);
//console.log(item);
};
$(document).on('click', '.product', function(){
var product = {Title: $(this).data('title'), ProductId: $(this).attr('id'), Price: $(this).data('price')};
console.log(product);
// here use ajax to add this product
});
body {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="products"></div>
Take a look at the Delegate jquery method!
Description: Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
So you basically need to bind the onClick event to the parent div, and pass a selector that will appear later on the child divs.
<script>
function onSelectGroup(Id) {
$.ajax(
//Do your ajax call here
).done(function (response) {
for (var i = 0; i < response.length; i++) {
let item = '<div class="event-target"></div>'
$(".products").append(item);
}})};
// Here's where the magic happens.
// We bind the event to the elements that have the 'event-target' class
//inside the element that have the 'products' class.
$('.products').on('click', '.event-target', function(){
console.log(this);
})
</script>
Warning: take care using delegate, if you use the wrong selector you can end up triggering the event for each element on the page, or even recursivelly (belive me, have made it a lot...)
Use data attributes to store any data & on click retrieve the data attribute.The code is not tested but hopefully it will work
let item = '<div class="col-md-3">' +
' <div class="Product-holder" ' +
'onclick="addProduct(this)"' +
' data-title="'+response[i].Title+'"' +
' id=' + response[i].ProductId + '>' +
'<img class="img-responsive" src="images/maxresdefault.jpg">' +
'<p class="product-title" style="color:white;margin-top:5px;text-align:center;"> ' + response[i].Title + '</p>' +
'</div>' +
'</div>';
$(".products").append(item);
function addProduct(product) {
console.log($(product).data('title'));
}
Also you need to delegate the event since they are dynamically created element
$("body").on("click",".Product-holder",function(){
console.log($(product).data('title'));
})
In this case the inline event handler that is onclick function will be redundant
Let me going to explant your code.
for (var i = 0; i < response.length; i++) {
let item = '<div class="col-md-3"> <div class="Product-holder" onclick="addProduct(' + response[i] + ')" id=' + response[i].ProductId + '><img class="img-responsive" src="images/maxresdefault.jpg"><p class="product-title" style="color:white;margin-top:5px;text-align:center;"> ' + response[i].Title + '</p></div></div>';
$(".products").append(item);
}})};
On these line of code, I saw that you have added strings to a variable.
but more exception response[i].ProductId seem like response[i] was an object.
but in Javascript you can't add an object to String by + operator, it will be return "string [object] string". What is solution for that??
Convert your object to JSON String like {"id": 123, "name": "Product name"}, that will show in html code like this onclick='addProduct({"id": 123, "name": "Product name"})' remember that onclick = ' not "

Removing elements by id using event Javascript dynamically

I have list of phones thats displaying as ul li. When user clicking button "buy" it creates new li with in another div "ordersDiv" user can delete his purchase from cart by clicking "Remove" And this must remove li with matching id.
Code that creates purchase:
$("#list").delegate("button",'click',function(){
var purchase = {id: null,name: null,price: null };
var purchases = [];
for(var i = 0; i < phones.length; i++){
if(this.id === phones[i].id){
purchase.id = phones[i].id;
purchase.name = phones[i].name;
purchase.price = phones[i].price;
//break;
purchases.push(purchase);
console.log(purchases);
$.each( purchases, function(i, purchase){
purchases.push("<li id='"+ purchase.id +"'>" + purchase.id +
"<br>" + purchase.name + "<br>" + "Price:" +purchase.price + "<br><button id='"+purchase.id+"' type='button' class='btn-default'>remove</button>" +"</li>" );
});
$('#ordersUl').append(purchases);
}
}
});
Code that supposed to remove li:
$("#ordersCartDiv #ordersUl").delegate("button","click", function() {
var buttonId = $(this).attr('id');
console.log(buttonId);
//$("li[id=buttonId]").remove();
$("#ordersUl").remove(buttonId);
console.log("test"); // code indentation
});
Problem is that this code doesn't removes anything.
you must pass a selector in remove function, like this:
$("#ordersUl").remove('#'+buttonId);
Use remove on button id.
$("# " + buttonId).remove();
No need to use ordersUl since id is unique(?).
If you don't have id unique:
$("#ordersUl #" + buttonId).remove(); // Will remove button inside #ordersUl
Remove the set of matched elements from the DOM.
Docs: http://api.jquery.com/remove/
$("#ordersUl").remove("#"+buttonId);
You should call remove function on element
$("li#"+buttonId).remove();
But ID is supposed to be unique, so it is bad idea to use it in this way. Use data- attributes or classes.

how to refresh the list in jquery javascript

Hi i m having one page with one textbox named search and one search button. When i'm searching anything for the first time it's showing me the right data but when i'm searching some other things for the next time then the elements which was listed before are also appended below of that new list. Suppose i'm searching state name by k it will give me right list of karnataka, kerala. But if i start to search again by g, it will show me in output as goa,gujrat,karnataka kerala. i tried using refresh option but it still not working. This is my js code
$.each(response.state, function (i, state) {
$('#statelist').append(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});
$("#statelist").listview("refresh");
and this is html
You are using .append() function. It appends whatever you append to the end of the list.
Check this link:
http://api.jquery.com/append/
Try using innerHTML property of the DOM model.
You could add
If(!('#statelist').html() == ""){
$(this).remove();
//execute rest of code that appends state list
}
Then do an else statement and execute your append code without removing()
UPDATE: a better option is to do this-
$.each(response.state, function (i, state) {
$('#statelist').html(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});

how to show list items separately in output using javascript

I have created one html which contains search box. After searching, I'm getting the data in list. But when I click on that I'm getting the value of all list item by using this
var text = $(this).text(); method
In my app, if I click on one item only it should give me only that value of list item not other. I'm making a mistake somewhere, but I don't know where.
Here is my code:
HTML
<ul data-role="listview" class="ui-li-icon">
<li id="list"></li>
</ul>
And here is my JavaScript code:
function successCallback(responseObj)
{
// alert(JSON.stringify(responseObj));
form.reset();
dataj=JSON.stringify(responseObj);
len=dataj.length;
for(i=0;i<len;i++)
{
var output = "<ul>" + responseObj.merchants[i].imageFileName+ " " + "<font size=3 color=green>" + responseObj.merchants[i].merchantName + "</font>" +"</ul>";
$('#list').append(output);
}
$('#list').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
}
So when I'm searching for some a item. I'm getting list of:
ab
abc
But when I clicked on it. I get value of both ab and abc. I just want only one value where I have clicked.
//replace your click event by below code
$('.ui-li-icon li').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
$('#list').append(output);
I believer list is the id you are giving to list items i.e.
Now, this will confuse the browser because id should be UNIQUE and here you are giving this id to all the list items.
If you fix this, your problem should be resolved!
Or you could simply attach click event using this
$('.ui-li-icon li').click //Your click event handler
It's very difficult to understand what you are asking. From what I can tell you're looking for something like this:
$('#list li').on('click', function(){
alert("index: "+$(this).index() + " value: "+ $(this).text());
});
Here's a fiddle http://jsfiddle.net/Jw8qz/

Categories

Resources