This question already has answers here:
JavaScript - Owner of "this"
(6 answers)
Closed 6 years ago.
I've got span inside an LI with a class of removeFile, when clicked, it should remove a file using jQuery $.get and then upon successful deletion, it should fadeout the containing LI. I can't figure out why this is not working, I can get it to alert(data) but not assign to a variable or execute the fadeOut() command.
$('#files').on('click', '.removeFile', function (event) {
event.preventDefault();
var fileUrl = $(this).data('file-url');
if (confirm('Are you sure you want to delete this file?')){
$.get('process.php', {'remove-file':fileUrl}, function(data){
if(data=='true'){
$(this).parent().fadeOut();
}
});
}
});
<li class="file">
<span class="file" data-file-url="http://demo.com/filemanager/files/test.txt" title="test.txt">test.txt</span>
<span class="removeFile" data-file-url="/files/test.txt"></span>
</li>
Inside ajax callback function this refers to jqXHR object, so you need to define it outside the ajax call as variable or set it the context option.
$('#files').on('click', '.removeFile', function (event) {
event.preventDefault();
var $this = $(this);
var fileUrl = $this.data('file-url');
if (confirm('Are you sure you want to delete this file?')){
$.get('process.php', {'remove-file':fileUrl}, function(data){
if(data=='true'){
$this.parent().fadeOut();
}
});
}
});
this in get() not referencing .removeFile. this refers to xhr object in the callback of get().
$('#files').on('click', '.removeFile', function (event) {
event.preventDefault();
var li = $(this).parent(); //added this line
var fileUrl = $(this).data('file-url');
if (confirm('Are you sure you want to delete this file?')) {
$.get('process.php', { 'remove-file': fileUrl }, function (data) {
if (data == 'true') {
li.fadeOut(); //changed this line
}
});
}
});
Related
This question already has answers here:
Making jquery plugins work after an Ajax call
(3 answers)
Chosen not working on elements from AJAX call
(2 answers)
Closed 1 year ago.
So I have this Jquery functions that I've created using delegations and call each functions in the documeny.ready.
$(document).ready(function () {
getContent();
getQuoteButtton();
popupModal();
plugins();
});
function getQuoteButtton() {
// button quote
$("body").on("click", ".btn-quote", function (e) {
var $this = $(this);
$this.toggleClass('quote-selected');
if ($this.hasClass('quote-selected')) {
$this.text('Selected');
} else {
$this.text('Select This Quote');
}
});
}
function getContent() {
// fire on click
$("body").on("click", 'nav#sidebar.get-qoute-sidebar ul li a', function (e) {
// setting target from data attributes
var $this = $(this),
target = $this.attr('data-target'),
container = $('#get_content');
container.load('pages/' + target + '.php');
});
}
function popupModal() {
/*Toggle popup-modal class */
$("body").on("click", ".popup-modal-toggle", function (e) {
$('.popup-modal').fadeIn().show();
});
//close popup button
$("body").on("click", ".popup-close", function (e) {
$('.popup-modal').fadeOut().hide(300);
});
}
function plugins() {
// phone number plugin initialized singapore and malaysia only
$("#phone-num").intlTelInput({
initialCountry: "SG",
onlyCountries: ['SG', 'MY'],
utilsScript: './resources/vendors/intl-tel-input-master/js/utils.js'
});
// Select tags with search bar
$(".chzn-select").chosen();
}
The other functions is working fine but when I call the plugins function it doesn't seem to load after using the getContent.
The getContent function is where I handle my ajax call to load each pages in the section using the div element #get_content
I don't understand why my plugins function is not working. Does anybody know why? Do I have to call each functions in plugins to use delegations also? if so, what's the process? Thanks.
EDIT - Correct Answer
I have find out the solution, in the getContent function, I also added the plugins() function inside to fetch it after ajax. I don't know why this question was closed even though I have a different approach in coding.
function getContent() {
// fire on click
$("body").on("click", 'nav#sidebar.get-qoute-sidebar ul li a', function (e) {
// setting target from data attributes
var $this = $(this),
target = $this.attr('data-target'),
container = $('#get_content');
container.load('pages/' + target + '.php', function (response, status, xhr) {
// include the plugins function after the content loads -> if no initialization function won't load
plugins();
});;
});
}
I got this javascript code to solve in a manner to use inner function but not able to use it. Please try to help me to use inner functions or do i need to modify this. I want to use inner functions on click on html element such as view and remove respectively;
var App = function(){
var url = 'api';
function view(event) {
var id = '??'; //here i have to receive id of the element(data-id)
$.ajax({
url: url + '/view/' +id,
data: data
}).done( function (data){
});
}
function remove(event) {
var id = '??'; //please determine the id
$.ajax({
url: url + '/remove/' + id ,
data: data
}).done( function (data){
});
}
function initialize() {
//
}
return {
//
}
}();
Try doing this:
For id you can do one thing, Save the id in data-id attribute of the element on which you want onClick listener and access it using Event-Delegation in javascript.
To use the inner method you don't need to return anything. Just do it this way :
var App = function(){
var url = 'api';
function view(event) {
//access the id attribute of event.target
}
function remove(event) {
//same
}
function initialize() {
//
}
App.view = view;
App.remove = remove;
};
//EDIT : instead of making it self-invoking, call the app function
App();
//to access it outside:
App.view("your_parameter");
App.remove("your_parameter");
EDIT : Instead of making it self-invoking, call the app function
Well it's pretty simple, use the $("#caller").click() function of our beloved
jQuery
Then inside the .click() function you can easily retrieve your id
Here you can find more on the .click() function
It will be something like this
$( "#view" ).click(function() {
id = document.getElementById("id").id;
//Here paste the code of your view function
});
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I use ajax to create dynamic div, and want to get notified when I click the "a" inside div which id='listall', but it's not working, why?
How to correct it. thanks
here is the code:
$(function(){
$.ajax({
type: "GET",
url: 'http://XXX:8080/',
dataType:'json',
contentType:"application/json",
success:function(data){
console.log(data);
var projectList="<ul style='list-style:none;'>"
for (var i = 0; i < data.data.length; i++) {
projectList += "<li><div id='listall'><a href='/projectDetail'>"+
"<img class='back' src='data.data[i]'></li>"
}
var projectList +="</ul>"
},
error:function(){
alert("connection error");
}
});
$('#listall').on('click', 'a', function (){
console.log('click!');
alert("finally");
});
});
Delegate the event
$('body').on('click', '#listall a', function (){
console.log('click!');
alert("finally");
});
you should use
$(document).on('click','#listall a',function(){
console.log('click!');
alert("finally");
});
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
My purpose is to define ajax method callback with jquery.
all DOM of parent div are loaded dynamically
i have define delete button foreach comments
and i want to get confirmation from twitter bootrap modal befor throw the ajax request : https://jsfiddle.net/r4sLt016/5/
this.deleteComment = function () {
self = this;
$("button[name='deleteComment']").each(function (index, el) {
$(this).unbind().bind('click', function (event) {
event.preventDefault();
var ref = $(this).attr('data-ref');
var callback = function () {
/*$.ajax({
url: '/path/to/file',
type: 'DELETE',
data: {param1: 'value1'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
});*/
alert("multiple");
}
self.confirm("Delete Comment ", "Are you sure you want \
to delete this Comment ?", callback);
});
});
}
this.confirm = function(head, question, callback) {
$(".modal-title").html(head);
var body = $("<p/>").text(question);
$(".modal-body").html(body);
$("#deleteModal").click(function(event) {
callback();
$('.customModal').modal('hide');
});
$('.customModal').modal('show');
}
You are binding the click event deleteModal element everytime you call the confirm() method!
So you have to unbind() and bind() again like you did at the deleteComment buttons.
Like this:
this.confirm = function(head, question, callback) {
$(".modal-title").html(head);
var body = $("<p/>").text(question);
$(".modal-body").html(body);
$("#deleteModal").unbind().bind('click', function(event) {
callback();
$('.customModal').modal('hide');
});
$('.customModal').modal('show');
}
>> Updated JSfiddle!
Les say I have some buttons with same class. On page load I am checking some value using ajax for each button. Depending on returned value of ajax request I want to add some class to the buttons, but it is not working,
$(document).ready(function(){
$('.add-remove-permissoion').each(function(){
var child = $(this).val();
var parent = $('#parent-name').text();
$.get('my-url', function(data){
if(data == 1){
$(this).addClass('glyphicon glyphicon-ok');
}else{
$(this).addClass('emptybox-blank');
}
});
});
});
I have checked that my ajax request is returning correct data. What is that I am doing wrong here?
The problem is the this reference inside the ajax callback, in the success callback this refers to the jqXHR object not the dom element reference that is why it is not working.
You can use a closure variable as given below to fix the problem
$(document).ready(function () {
$('.add-remove-permissoion').each(function () {
var $this = $(this),
child = $this.val();
var parent = $('#parent-name').text();
$.get('my-url', {}, function (data) {
if (data == 1) {
$this.addClass('glyphicon glyphicon-ok');
} else {
$this.addClass('emptybox-blank');
}
});
});
});
this in the context of the $.get handler doesn't refer to the element of the current iteration. Each function has it's own this value. You have several options.
Use the second parameter of the each callback.
$('.add-remove-permissoion').each(function(index, element) {
Use $.proxy or Function.prototype.bind method for setting the this value of the handler.
$.get('my-url', function(data) {
// ...
}.bind(this));
Cache the this value of the each handler and use it in your $.get handler.
var elem = this;
$.get('my-url', function(data) {
// ...
$(elem)...
});
Also note that there is a syntax error in your code:
$.get('my-url'}, function(data){
// -----------^
Problem is $(this) within ajax call does not refer to the button clicked.
Replace $(this).addClass with myElement.addClass. Create myElement within click event just before the ajax call: var myElement = $(this).