I am populating a list of friends using an ajax call to a php script that returns a json array . I am populating each list item with the friends name and putting a button next to it. The name and the button are both in the list item. I want to find the friends name when i click on the button so I can then post it to another script that will remove them from the friends list. As well, I need to select the entire list item when the user clicks on the side button so I can immediately remove it from the unorganized list. The issue that I am having is that I am trying to call something like $(this).find(‘font’).text(); but this is only referring to the button that was clicked and not the entire list item. I’m sure it’s something simple that I’m overlooking but it has been giving me grief for too long now.
The HTML
<ul data-role="listview" data-inset="true" id="friends" data-theme="a"
data-divider- theme="a">
<li data-role="list-divider"><h3>Friends</h3></li>
</ul>
The Javascript
function getFriendsList(){
var searchType = "friend";
var friendList = "";
var friendName = "";
var friendPoints = "";
var name = "";
$.post('friendScript.php', {
searchType : searchType,
}, function(data){
$.each(data, function(index, value){
$.each(value, function(index, item){
if(index == 0){
friendName = item;
}
if(index == 1){
friendGratii = item;
}
});
friendList += '<li class="friend"><a href=""><h3>' +
'<font id="friendsName">' +
friendName +
'</font>' + " - " +
friendPoints +
'</h3></a>' +
'<a href="" id="defriend" data-icon="delete">' +
"Remove Friend " + '</a>' + '</li>';
});
$('#friends').append(friendList).listview('refresh');
$('#friends').find('li:has(font)').find('#defriend')
.unbind("click").bind("click",
function(){
var clickedFriend = $(this);
name = $(this).find('.friend').text(); //HERE IS THE PROBLEM IT
//ALWAYS RETURNS AN EMPTY STRING
$.post('defriendScript.php', {
friendName : name,
}, function(data){
if(data != "success"){
alert(data);
}
if(data == "success"){
$(clickedFriend).remove();
}
});
});
}, "json");
};
You are doing this:
$(this)will be the#defriendelement, which is a child of your<li>. Doing$(this).find('.friend')will search for elements with classfriendwithin your button. whichi is not what you want. Try this: