I am creating an image dynamically in Jquery and trying to add a control to it When the user clicks the image, I want to popup alert() with the image's id. But I couldnt succeed to show id of the image in the alert box. Please help me display the id of the image in alert box.
here is the code display the alert box
function category_follow(search_txt) {
alert(this.Attr('name'));
}
here is the code where I create the image dynamically
$.ajax({
url: 'HoverCard_WebService.aspx?q=' + encodeURIComponent(span_text),
type: 'GET',
dataType: 'json',
beforeSend: function () {
$(".hovercard").prepend('<p class="loading-text">Yükleniyor...</p>');
},
success: function (data) {
$(".hovercard").empty();
$.each(data, function (index, value) {
var search_txt = 'TestArif4';
result += '<div><button class=\'takibe_al\' name=\'test_name\' id=\'btn_test_id\' onClick=category_follow(\'' + value.id + '\')><img id=\'img_category_follow\' src=\'images/hover_card_plus_icon.png\' class=\'hover_cursor_hand\' /></button></div>';
});
},
What are you doing with your "result" variable?
function category_follow(search_txt) {
alert(this.Attr('name'));
}
this refers to the DOM Element and "Attr" should probably be "attr" if you are using jQuery.
I recommend you to use jQuery to bind your events instead of using the element attribute onClick;
$(document).on('click', '.takibe_al', function(event) {
var $this = $(this);
alert('Clicked on element with name = ' + $this.attr('name'));
});
See on.
Related
I am trying to create a dropdown menu that I dynamically insert into using jQuery. The objects I'm inserting are notifications, so I want to be able to mark them as read when I click them.
I have an AJAX call that refreshes the notifications every second from the Django backend.
Once it's been refreshed, I insert the notifications into the menu.
I keep an array of the notifications so that I don't create duplicate elements. I insert the elements by using .append(), then I use the .on() method to add a click event to the <li> element.
Once the click event is initiated, I call a function to .remove() the element and make an AJAX call to Django to mark the notification as read.
Now my problem:
The first AJAX call to mark a notification as read always works. But any call after that does not until I refresh the page. I keep a slug value to identify the different notifications.
Every call I make before the refresh uses the first slug value. I can't figure out why the slug value is tied to the first element I mark as read.
Also, if anyone has a better idea on how to approach this, please share.
Here's my code:
var seen = [];
function removeNotification(elem, urlDelete) {
elem.remove();
console.log("element removed");
$.ajax({
url: urlDelete,
type: 'get',
success: function(data) {
console.log("marked as read");
},
failure: function(data) {
console.log('failure to mark as read');
}
});
}
function insertNotifications(data) {
for (var i = 0; i < data.unread_list.length; i++) {
var slug = data.unread_list[i].slug
var urlDelete = data.unread_list[i].url_delete;
if (seen.indexOf(slug) === -1) {
var elem = $('#live-notify-list').append("<li id='notification" +
i + "' > " + data.unread_list[i].description + " </li>");
var parent = $('#notification' + i).wrap("<a href='#'></a>").parent();
seen.push(slug);
$( document ).ready(function() {
$( document ).on("click", "#notification" + i, function() {
console.log("onclick " + slug);
removeNotification(parent[0], urlDelete);
});
});
}
}
}
function refreshNotifications() {
$.ajax({
url: "{% url 'notifications:live_unread_notification_list' %}",
type: 'get',
success: function(data) {
console.log("success");
insertNotifications(data);
},
failure: function(data) {
console.log('failure');
}
});
}
setInterval(refreshNotifications, 1000);
I really don't know what do you mean with parent[0] in
removeNotification(parent[0], urlDelete);
I think you can simply try $(this)
removeNotification($(this), urlDelete);
but to be honest I find to put
$( document ).ready(function() {
$( document ).on("click", "#notification" + i, function() {
console.log("onclick " + slug);
removeNotification(parent[0], urlDelete);
});
});
inside a loop .. its bad thing try to put it outside a function and use it like
$( document ).ready(function() {
setInterval(refreshNotifications, 1000);
$( document ).on("click", "[id^='notification']", function() {
console.log("onclick " + slug);
removeNotification($(this), urlDelete);
});
});
and try to find a way to pass a urlDelete which I think it will be just one url
In my Ajax success function i created button and on click i am calling a function.
The problem:
The page reloads based on the timer in set interval but when i click the button it will call the function based on the number of times the page reloaded.
For example:
If page reloads 5 times and then i call a function on clicking that button-it will call that function 5 times.
if it reloads 10 times then function call is for 10 times.
Please advice what i am doing wrong?
Here is the code:
$(document).ready(
function() {
setInterval(function() {
$.ajax({
type: 'GET',
url: 'Refresh',
success: function(data) {
var trHTML = '';
$.each(data, function(i, item) {
var buttonVar = ('<button id="bt21" class="btn121">' + "STOP" + '</button>');
trHTML += '<tr><td>'+buttonVar+'</td></tr>'
});
$('#test1').append(trHTML);
$(document).on('click','#bt21', function(event) {
var rownum1 = $(this).closest('tr').index();
stopTest(data[rownum1].process_id);
});
}
});
}, 5000);
});
You have set the AJAX call to be made every 5 seconds. Each time time this function is called, you are also attaching the click event on the button you append. So there will be multiple event handlers attached to the same element. You need to clear any existing event handlers on that element before you attach another if you want to stick to your current code. Here's how to do it:
$(document).off('click', '#bt21');
$(document).on('click','#bt21', function(event) {
var rownum1 = $(this).closest('tr').index();
stopTest(data[rownum1].process_id);
});
Each time the page is refreshed from your ajax call a new event listener is bound to the button in memory. You need to clear the event listeners then create a new one.
$(some element).unbind().on(...........);
I always unbind event listeners created in an ajax call if anything to keep the browser memory from being over loaded or to prevent the issue you are having.
$(document).ready(
function() {
setInterval(function() {
$.ajax({
type: 'GET',
url: 'Refresh',
success: function(data) {
var trHTML = '';
$.each(data, function(i, item) {
var buttonVar = ('<button id="bt21" class="btn121">' + "STOP" + '</button>');
trHTML += '<tr><td>'+buttonVar+'</td></tr>'
});
$('#test1').append(trHTML);
$(document).unbind().on('click','#bt21', function(event) {
var rownum1 = $(this).closest('tr').index();
stopTest(data[rownum1].process_id);
});
}
});
}, 5000);
});
First you are appending buttons on refresh that have the same id attribute so that's going to cause you issues at some point.
What you need to do is move your click event outside of the interval function and ajax callback. Add the process id to the button in a data attribute and delegate a click event to the button so it will work even though the elements haven't been created in the DOM when the page loads.
Here's an example although I'm not sure if it works (can't really simulate this easily):
$(document).ready(function() {
setInterval(function() {
$.ajax({
type: 'GET',
url: 'Refresh',
success: function(data) {
var trHTML = '';
$.each(data, function(i, item) {
var buttonVar = '<button class="btn" data-process-id="' + item.process_id + '">' + "STOP" + '</button>');
trHTML += '<tr><td>'+buttonVar+'</td></tr>'
});
$('#test1').append(trHTML);
}
});
}, 5000);
$('#test1').on('click', '.btn', function() {
stopTest( $(this).data('process_id') );
});
});
I have the following javascript when my script is loaded:
var current_selected_note = $('#new_note');
current_selected_note.addClass('hover active');
$('#note-item-lists').on('click', '.list-group-item', function () {
//removes the hover color from the previous selected
current_selected_note.removeClass('hover active');
// sets the currently selected equal to the selected note
current_selected_note = $(this);
// adds the hover active to the currently selected
current_selected_note.addClass('hover active');
//adds the title of the currently selected to the title input field
$('#txt_new_note_title').val($(this).find('Strong').text());
selected_note_id = $(this).get(0).id;
getNote(selected_note_id);
load_comments(selected_note_id);
});
$( "#note-item-lists").find('li').first().trigger( "click" );
Now AFTER this is loaded i click one of my buttons which has the following javascript:
$('#note-item-lists').on('click','.close',function(){
var r = confirm('Are you sure you wish to delete "'+$(this).next('div').find('.new_note_title').text()+'" ?')
if(r == true){
deleteNote($(this));
$( "#note-item-lists").find('li').first().click();
}
})
function deleteNote(button){
var id = button.closest('li').get(0).id;
$.ajax({
type: 'POST',
url: '/solo/ajax_delete',
dataType: 'json',
data: {
id: id
},
success: function (data) {
}
});
button.closest('li').remove();
}
When this happens (i debug it) and the event function is called first 1 time (adding the class correctly) but is then happens immediatly again.
Anyone tried this before?
Try this, It will call one time.
$('#note-item-lists .close').on('click',function(){
alert("Hello");
});
Try using .off()
$('#note-item-lists').on('click', '.list-group-item', function () {
$(this).off(); //add this here
I have an application that displays web pages which contains source reference, when user hover above the source reference a tooltip with extra information appears.
I want to change tooltip text dynamically to responseText if communication with the server was successful (see method below) - but I don't know how .
(I already make sure the the respomseText contains the right data)
the tooltip is generated and it's data is sent by this jQuery code:
$(document).ready(function() {
$('table a').on('mouseenter._do_submit', _do_submit);
$('table a').tooltip({
tooltipClass: "coolToolTip",
content: function() {
var element = $( this );
return '<p class=toolTipP>' +element.text(); + '</p>';
}
});
$('table').bind('mouseleave._remove_icon', _remove_icon);
function _remove_icon(event) { $(event.target).find('img').remove(); }
function _do_submit(event) {
$event_origin = $(event.target);
$event_origin.find('img').remove();
ajax_sender( $event_origin );
}
function ajax_sender(event_origin_obj) {
$('<img src="./js/ajax_ani.gif" />').appendTo(event_origin_obj);
url= 'http://localhost:8080/zoharTranslator/ReadZohar';
var xhr = $.ajax({
type: 'GET',
url: url,
data: 'command=source&src=' + event_origin_obj.text(),
beforeSend: beforeSending,
success: on_success,
error: log_error_message
});
function on_success(data) {
event_origin_obj.find('img').remove();
$(document).removeAttr("title");
event_origin_obj.attr( "title", data);
console.log(xhr);
}
function log_error_message(xhr) {
...
}
function beforeSending(xhr) {
...
}
}
});
You can always change the content of your tooltip after its created by using it's setter like this...
$( ".selector" ).tooltip( "option", "content", "Awesome title!" );
-- 2ND UPDATE --
OK, I figured out how to get the jQuery UI added to jsFiddle. This is how I would solve your problem: http://jsfiddle.net/spZ69/3/
Obviously the ajax call won't work but just replace the url ajax/test.html with your url that returns text and it will replace the tooltip's text.
I've created a function which loads content and writes into html. For some reason the function is displayed after two clicks instead of one. Any idea how to make it so it load and display the info with just one click?
function getFuncDoc(funcName, targetDivId) {
var webServiceCall = funcName;
$.ajax({
type: "get",
url: webServiceCall,
success: function(doc) {
$('#' + targetDivId).load(doc, function(){
$('#' + targetDivId).toggle(
function() {
$('#' + targetDivId).css('padding', '10px');
$('#' + targetDivId).html(doc);
});
});
},
error: function(request, status, error) {
return 'Error';
}
});
}
Check if the targeted element (targetDivId) has display:none before the toggle() is triggered.
If that's not the case, then you'll need to add this attribute to your element in CSS.
toggle()-ing an element with display:block or display:inline or display:inline-block will hide the element and set its attribute to display:none, hence why you need to trigger it twice for the content to be shown.
Here is a live demo.