JQuery delete closest element from Firebase - javascript

So I append my chatbox with records from Firebase, but I would also like to delete those records. Now I am not a genious with JQuery and thus I would like to know what should be used. In the original example they use data-id's
//Delete when clicking element
jQuery('body').on('click', 'a#message', function() {
var $rec = $(this).closest('[data-reactid]');
var id = $rec.attr('data-reactid') || null;
if( id ) {
// Delete nested elements
$rec.find('[data-reactid]').each(function() {
ref.child($(this).attr('data-reactid')).remove();
});
// Delete record
ref.child(id).remove();
}
return false;
});
ref.on('child_removed', function (snapshot) {
$('ul.chat-messages').find('[data-reactid="'+snapshot.name()+'"]').remove();
});
This is the original example:
http://jsfiddle.net/katowulf/QnUpb/
My output is a bit else than the example, it is build as follow:
<ul class="chat-messages" data-reactid=".1.1.1.1">
<ul id="ulrecords">
<li id="limessage">[some message here]</li>
<li>[additional info for message</li>
</ul>
</ul>
Basically in the first 'li' i have a to activate the JQuery and when i click that delete button in the 'li', I want to delete the "ulrecords"
Hope anyone can help me with this

Related

How to recognize which button is clicked

I am using wordpress for my blog posts - all posts are fetched on the same page and each post has button, I need to be able to recognise which button of which post was clicked.
I can do it only with hardcoded data, but I am unsuccessful with dynamic ones.
I tried to give a trigger button common class and then detect it in JS.
<div class="row">
<button class="common-button-class">CLICK</button>
</div>
let openButton = document.getElementsByClassName(
'common-button-class'
);
if (openButton != null) {
document.querySelector('.common-button-class')
.addEventListener('click', (event) => {
// tried detect event id here unsuccessfully
});
}
Is there function of how to know which post is being triggered?
Use querySelector instaid of getElementsByClassName
let openButton = document.querySelector('.common-button-class');
openButton.onclick = function() {
//Your code here
};
you can use jquery in WordPress
first add properties just like data-id and keep post id in it.
then :
$(document).on("click",".common-button-class", function () {
var clickedBtnID = $(this).data('id');
alert('you clicked on button #' + clickedBtnID);
});

incorrect array push and splice?

I am making an invite system. I am using ajax to load a list of search results. When an li is clicked I push the user's id into an array and append a checkmark to the li to let them know they were added to the list.
The push is working but the splice is not. Also when the list is empty the submit button does not return to its disabled state and original styling.
Lastly, when I search again (re-calling the ajax) it removes the appended checkmark. Is there a way with javascript to store which user was click on and retain the appended checkmark when they search for another name?
(^ when i load the results with ajax i check if a person is invited or not in my db i could do it so if they are already invited a click would delete from table..if not on li click i insert with an ajax and setTimeout on success.. do you think that would be a bad practice?)
Below is my html && script
HTML
<li class='inviteUser'>
<img src='$usersProfilePhoto' alt=''>
<h2>$usersname</h2>
<input type='hidden' value='$otherUserID'>
<span></span>
</li>
$(function(){
var inviteList = new Array();
$(document).on('click', '.inviteUser', function(){
var inviteUserID = $(this).children('input').val();
inviteList.push(inviteUserID)
$(this).children('span').append("<p class='remove'>✓</p>");
if(inviteList.length > 0) {
document.getElementById('imcSubmitButton').disabled = false;
$('#imcSubmitButton').css({'opacity':'1'});
} else {
document.getElementById('imcSubmitButton').disabled = true;
$('#imcSubmitButton').css({'opacity':'0.25'});
}
});
$(document).on('click', '.remove', function() {
inviteList.splice($(this).index(), 1);
$(this).remove();
});
});
The problem is that the indexes in inviteList don't correspond to indexes in the HTML. You should search for the element in inviteList that contains this item's userID, and splice that out.
$(document).on('click', '.remove', function() {
var userid = $(this).parent().siblings("input").val();
var index = inviteList.indexOf(userid);
if (index != -1) {
inviteList.splice(index, 1);
}
$(this).remove();
});
To solve your problem with remembering which users were invited, the code that processes the AJAX responsee can use:
if (inviteList.indexOf(userId) != -1) {
// Add checkmark
}
Things would be easier if inviteList were an object rather than array, using userids as keys.

Javascript - How to Remove DOM elements using click events and classes?

I am having some difficulty using parentNode.removeChild(). I have a list of 'items' in an un-ordered list, each have there own delete button. I am trying bind a click event to each individual button that will delete it's respective parent 'item'.
My code so far:
<ul class="list">
<h2>This is a list</h2>
<li class="item">
<h3>Some Item</h3>
<button class="delete">Delete</div>
</li>
<li class="item">
<h3>Some Item</h3>
<button class="delete">Delete</div>
</li>
<li class="item">
<h3>Some Item</h3>
<button class="delete">Delete</div>
</li>
</ul>
var childElements = document.getElementsByClassName('item');
var buttonElement = document.getElementsByClassName('delete');
function deleteItem(buttonsClass, childClass) {
for (var i=0;i<buttonsClass.length;i++) {
var child = childClass[i];
buttonsClass[i].addEventListener('click', function(child) {
childClass[i].parentNode.removeChild(childClass[i]);
}, false);
}
}
deleteItem(buttonElement, childElements);
I know there is an easier way to do this with jQuery but i really want to solve this with plain javascript. Thank you for any and all help.
This is a perfect case for event delegation. No need for jQuery at all:
(function(window, htmlElement) {
'use strict';
htmlElement.addEventListener("click", handleClick, false);
function handleClick(event) {
if (event.target.classList.contains("delete")) {
event.preventDefault();
removeItem(event.target);
}
}
function removeItem(button) {
var item = getItem(button),
confirmMessage;
if (item) {
confirmMessage = item.getAttribute("data-confirm");
if (!confirmMessage || window.confirm(confirmMessage)) {
item.parentNode.removeChild(item);
}
}
else {
throw new Error("No item found");
}
}
function getItem(button) {
var element = button.parentNode,
item = null;
while (element) {
if (element.nodeName === "LI" || element.nodeName === "TR") {
item = element;
break;
}
element = element.parentNode;
}
return item;
}
})(this, this.document.documentElement);
You have one click handler for the entire page, regardless of how many delete buttons you have. This should also work for list items or table rows, and by specifying a data-confirm attribute on your buttons, it will pop up a confirm box before removing it.
<button type="button" class="delete"
data-confirm="Are you sure you want to delete this item?">
Delete
</button>
You can also easily change this so it uses another attribute to find the delete button:
<button type="button" class="delete"
data-delete
data-confirm="...">
Delete
</button>
Just change the condition of the if statement in the handleClick function to:
if (event.target.hasAttribute("data-delete")) {
event.preventDefault();
removeItem(event.target);
}
This decouples your behavior from styling. You can use the delete class name for styling, and the data-delete attribute for JavaScript behavior. If you need to change the name of the CSS delete class for any reason, or use a different class, because you decide to use a third party CSS framework like Bootstrap, then you don't need to change a single line of JavaScript.
The last advantage here is that the click handler is attached to the document.documentElement object, which is available the moment JavaScript begins executing and represents the <html> element. No need for jQuery's document ready event handler. Just attach the click handler and import the script at any point on the page.
The problem is that your childClass[i] that you call when you click an element, is not what you expect when you define the function.
You should use event.target for catch the element clicked
var childElements = document.getElementsByClassName('item');
var buttonElement = document.getElementsByClassName('delete');
var _handler = function(e) {
e.target.parentNode.parentNode.removeChild(e.target.parentNode);
}
function deleteItem(buttonsClass, childClass) {
for (var i=0;i<buttonsClass.length;i++) {
buttonsClass[i].addEventListener('click', _handler, false);
}
}
deleteItem(buttonElement, childElements);
-- edit --
If you want to use the original approach, then you can solve it in this way:
function deleteItem(buttonsClass, childClass) {
for (var i=0;i<buttonsClass.length;i++) {
(function(child) {
buttonsClass[i].addEventListener('click', function(e) {
child.parentNode.removeChild(child);
}, false);
})(childClass[i]);
}
}
With encapsulation (function(encapsulatedChild) { })(child) you can store the value of child in a context that does not change during the next cycle.
Looks like you want to bind a click event to delete buttons, and on that event delete that item.
You need to fetch the child classes individual buttonsClass elements.
function deleteItem( childElements )
{
Array.prototype.slice.call( childElements ).forEach( function( item ){
var deleteChildren = item.getElementsByClassName( "delete" );
Array.prototype.slice.call( deleteChildren ).forEach( function( deleteBtn ){
deleteBtn.addEventListener('click', function()
{
this.parentNode.removeChild( this );
}, false);
});
});
}
or even more simply, just pass the list of buttons on clicking which parent item will be deleted
function deleteItem( buttonElement )
{
Array.prototype.slice.call( buttonElement ).forEach( function( button ){
button.addEventListener('click', function()
{
this.parentNode.removeChild( this );
}, false);
});
}

How to get ID of listview item Clicked. [javascript / jquery / jquery mobile]

I need advice on how to detect which <li> is tap/click by the user, then write the 'ID' of the tap/clicked <li> into Localstorage, then use the saved Localstorage to retrieve data for Detail Page.
I'm new to javascript/jquery, if you can provide some simple example code will be very much appreciated.
I know how to write Localstorage, read Localstorage, get JSON data from server API, generate Loop for Listview with unique ID for each <li>.
What I need is, how to use JS to make <li> clickable (link to Detail Page) and write to Localstorage at the same time.
I have tried:
$('.liClass').click(function() { //block of code to write Localstorage };
But the <li> is not clickable and no key/value written to Localstorage. Not to mention to detect which <li> is clicked (this I have no idea).
Please advice, thank you.
Code update:
//Show restaurant listing - NOTE: This is not first page. Link from other Page.
$('#restaurantList').on("pagebeforecreate", function() {
$.getJSON("http://mydomain.com/api/restaurant", function( data ) {
function rstListing(data) {
if ($.isEmptyObject(data) === true) {
alert ('JSON return empty');
} else {
for (i=0; i<data.length; i++){
$('#restaurantListing').append('<li id="' + data[i].restaurant_id + '" class="rstList"><img src="http://mydomain.com/file/img/' + data[i].restaurant_logo + '"><h2>' + data[i].name + '</h2><p>' + data[i].city + '</p></li>');
$('#restaurantListing').listview('refresh');
}
}
}
rstListing(data);
}
);
});
//Listview link to Detail Page
$(document).ready(function(){
$('.rstList').click(function() {
var id = $(this).attr("id"); // Get the ID
alert(id);
console.log(id);
});
});
Also tried:
//Listview link to Detail Page
$('#restaurantList').on("pageload", function() {
$('.rstList').click(function() {
var id = $(this).attr("id"); // Get the ID
alert(id);
console.log(id);
});
});
You don't need to make any <li> element to be clickable by your self, when you add the click event to any element, that will be triggered when the item is clicked.
Your problem will basically be that the element is not loaded when the event is bind to it. So you have to add your code inside document ready event like this.
$(document).ready(function(){
$('.liClass').click(function() {
var id= $(this).attr("id"); // Get the ID
};
});
$('.liclick').click(function() {
alert($(this).attr("id"));//Get id of clicked li
localStorage.setItem($(this).attr("id"),$(this).attr("id")); //stored into localStorage
alert("Data from localStorage "+localStorage.getItem($(this).attr("id"))); // get stored id
});
Working Fiddle
You will need to use the event delegation to assign the click event since you are building the HTML DOM dynamically via JSON request, thus not being able to locate the 'li' elements at the time of the page load. So, it would look like:
$(document).on("click", ".rstList", function (event) {
// click event
}
See this link for more details:
jQuery event delegation
I have solved my problem with the example code provided by stackoverflow member here. My previous problem is because I separate the creation of the listview and bind the click listener in two different page event.
After testing the page event sequence, I'm now putting the click listener into the same page event instead of separate to two. Now my code look like this, hope this will help someone bump into the same problem as me:
//Show restaurant listing
$('#restaurantList').on("pagebeforecreate", function() {
alert('pagebeforecreate event triggered');
$.getJSON("http://mydomain.com/api/restaurant", function( data ) {
function rstListing(data) {
if ($.isEmptyObject(data) === true) {
alert ('JSON return empty');
} else {
for (i=0; i<data.length; i++){
$('#restaurantListing').append('<li id="' + data[i].restaurant_id + '" class="rstList"><img src="http://mydomain.com/file/img/' + data[i].restaurant_logo + '"><h2>' + data[i].name + '</h2><p>' + data[i].city + '</p></li>');
$('#restaurantListing').listview('refresh');
}
}
}
rstListing(data);
alert('rstListing() executed');
$('.rstList').click(function() {
alert($(this).attr("id"));//Get id of clicked li
localStorage.setItem($(this).attr("id"),$(this).attr("id")); //stored into localStorage
alert("Data from localStorage "+localStorage.getItem($(this).attr("id"))); // get stored id
});
}
);
});

How to get the selected check boxes in Kendo Mobile

I'm new to kendo I have a list populated from a data source (with template : Each list item has mobile switch in it).I need to get all the id's of selected mobile switches when I clicked on a single button. Can anyone let me know how to do that in kendo ?
Cheers,
Chinthaka
I solved that Using following code (Only Active Items checked items)
var checkedWorkCentersIds = new Array();
$('#workcenters :checkbox:checked').map(function () {
if (this.checked == true) {
checkedWorkCentersIds.push(this.id);
}
});
Without the code it is hard to give an exact answer, but you should be able to just loop over the data items in the array and find the ones that are selected.
For example:
var dataSource = new kendo.data.DataSource( ... );
function getSelected() {
return $.grep(dataSource.view(), function (item) {
return item.selected;
});
}
Assuming the switches/checkboxes are bound to the "selected" property.
In response to your comment, you can get the selected checkbox element IDs with jQuery:
$("#workcenters :checkbox:checked").map(function (index, checkbox) {
return $(checkbox).attr("id");
});

Categories

Resources