This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
$(function() {
$(".reqdeb").click(function() {
console.log("Working");
var req_id = $(this).attr("id");
var info = 'id=' + req_id;
if (confirm("Are you sure you want to delete this request?")) {
$.ajax({
cache : false,
type : "POST",
url : "del_req.php",
data : info,
success : function() {
}
});
$(this).parents("tr").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
This is the code that stops working after a few tries of pressing the button and the code that causes it to stop working is this:
function autoRefresh_div(){
$("#refresh").load("reqs.php");
$("#nrref").load("numreq.php")
}
setInterval('autoRefresh_div()', 5000);
Seems you are replacing the existing elements thus event handlers are also removed. You can use .on() method with Event Delegation approach.
General Syntax
$(document).on('event','selector',callback_function)
Example
$(document).on('click', ".reqdeb", function(){
//Rest of your code
});
In place of document you should use closest static container for better performance.
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
When I reload the page, I call ajax to get the data and display it on the screen.
<div class="empList"><ul></ul></div>
<script>
$(document).ready(function() {
$.ajax({
url: 'process.php',
method: 'post',
dataType: "json",
data: {
action: "employeelist"
},
success: function(data) {
var trHTML = '';
$.each(data, function(i, item) {
trHTML += '<li><div class="employeeShareWrap">Share</div></li>';
});
$('.empList ul').append(trHTML);
}
})
});
//clicking on the share button
$(".employeeShareWrap>a").click(function(e) {
e.preventDefault();
console.log('hi');
alert("hello");
});
// this is the second way i tried
/*
$(".employeeShareWrap>a").click(function(){
var otherInput=$(this).data("id");
alert(otherInput);
alert("hello");
});*/
<script>
As of now, I am displaying the share button for testing purposes. Now My issue is when I am clicking on the share button then I am not getting any alert. There is no error in the console.
And if I added directly in the HTML then it's working.
<li><div class="employeeShareWrap">Share</div></li>
<script type="text/javascript">
$(".employeeShareWrap>a").click(function(e){
e.preventDefault();
console.log('hi');
alert("hellow");
});
</script>
Is there any issue with my script or I am displaying it in a wrong way?
This is because the anchor tag hasn't been created yet, by the time you try to attach your listener to it. Consider using the on method instead:
$(document).on('click', '.employeeShareWrap > a', function(e){
e.preventDefault();
console.log('hi');
alert("hellow");
});
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I have a select, lets call it A. When i choose an option from A, with ajax, i load an another select with options into a div. Lets call this second select B.
I have some ajax onchange code on B, but it does nothing, and it gives no error also.
I think, the "site doesnt see the B select", because it isnt in the source code, ajax loads it into a div.
What would be the solution for this?
$('#fizetes_select').on('change', function() {
var SelectedValue = this.value;
if(SelectedValue != 0 )
{
$.ajax({
type: 'POST',
url: 'files/get_fizetes_text.php',
data: { id: SelectedValue },
dataType: "html",
cache: false,
beforeSend: function(){
$('#preloader_fizetes').show();
},
success: function(data)
{
var result = $.trim(data);
$('#fizetes_result').html(result);
},
complete: function(){
$('#preloader_fizetes').hide();
}
});
}
return false;
});
Thats the onchange code for the B select, i only want to display some text with it. The ID-s are correct, i didnt write it bad, i chekced. Its in document ready.
Are you sure #fizetes_select isn't entering the DOM after this .on() declaration?
Try using document event binding with a targeted element instead.
$(document).on('change', '#fizetes_select', function(e) {
// do your thing here
});
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
Good day,
I have a piece of code that is aimed to perform action on mouse click. First I have made a function that scrolls screen on element when I perform a click on another element:
(function($) {
$.fn.goTo = function() {
$('html, body').animate({
scrollTop: $(this).offset().top + 'px'
}, 'fast');
}
})(jQuery);
than I assign this function to specific DOM elements:
$('#collapse1').on('shown.bs.collapse', function () {
$('#s1').goTo();
});
$('#collapse2').on('shown.bs.collapse', function () {
$('#s2').goTo();
});
$('#collapse3').on('shown.bs.collapse', function () {
$('#s3').goTo();
});
$('#collapse4').on('shown.bs.collapse', function () {
$('#s4').goTo();
});
etc...
"shown.bs.collapse" is actually from bootstrap collapse.js.
"This event is fired when a collapse element has been made visible to the user (will wait for CSS transitions to complete)."
The code is working but it is really not looks good. Is there the way to make some sort of cycle? Standard "for" is not working:
var collapseNumber = jQuery.makeArray(document.getElementsByClassName("panel panel-default"));
for (var i = 0; i < collapseNumber.length; i++) {
$('#collapse' + i).on('shown.bs.collapse', function () {
$('#s' + i).goTo();
});
}
created array is for getting actual number of elements, which I need to put in the cycle.
The problem you have is the infamous for loop issue where the value of i is the last value. But there is no reason to have to loop when a simple data attribute can be used.
Just use a data-attribute to select and link the things
<div data-goto="#s1">...</div>
and the JavaScript
$('[data-goto]').on('shown.bs.collapse', function () {
var selector = $(this).data("goto");
$(selector).goTo();
});
I have a snippet in my project similar to the one seen below:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$('#this_container').fadeIn();
}
});
The above snippet is working. When thisCondition evaluates to true, the container does fade in. However, I also have the snippet below that is not functioning as expected. It binds to show so that when the container fades in an event will be triggered:
$('#this_container').bind('show', function() {
$.ajax({
...
});
});
Shouldn't the snippet above react to line 5 in the change event handler? Why is the bind method not triggering?
Confirmed that show is not a valid nor jQuery-triggered event.
But you can trigger it yourself!
Try something like this :
$('#this_container').fadeIn("slow", function() {
$(this).trigger("show");
});
The show is not a valid event, neither is triggered by jQuery. You need to construct your script in a different way altogether:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$.ajax({
success: function () {
$('#this_container').fadeIn();
}
});
}
});
So, you can try to bring the AJAX content, and upon a successful request, you can show the container.
try to use :
$('#this_container').fadeIn( "slow", function() {
// Animation complete
$.ajax({
...
});
});
<div id="divItems"><div id="divItemsContent"></div></div>
I think i know what the problem is, just don't know how to solve it. Here is the code:
function SplitOrder() {
var SplitTable = $.ajax({
url: 'AjaxActions/SplitTable.aspx?FromObjectID=' + $('#hidObjectID').val() + '&ToObjectID=' + ObjectID[1],
async: false
}).responseText;
var dialog = $('#divItems').dialog({
autoOpen: false,
height: 500,
width: 600,
title: 'פיצול שולחן'
});
var content = $("#divItemsContent");
content.html("");
content.html(SplitTable);
dialog.dialog("open");
//הפעולות על החשבונות
/************************************************/
$('#imgLeftArrow').click(
function() {
$(this).css("background-color", "white");
//AJAX הבאת נתוני רשומת ההזמנה מהשרת ב
var SplitTable = $.ajax({
url: 'AjaxActions/SplitUpdate.aspx?FromObjectID=' + $('#hidObjectID').val() + '&ToObjectID=' + ObjectID[1] + '&ItemID=' + $('#hidItemID').val() + '&ItemAmount=' + $('#hidItemAmount').val(),
async: false
}).responseText;
content.html("");
content.html(SplitTable);
});
$('#imgRightArrow').click(
function() {
//AJAX הבאת נתוני רשומת ההזמנה מהשרת ב
var SplitUpdate = $.ajax({
url: 'AjaxActions/SplitUpdate.aspx?FromObjectID=' + $('#hidObjectID').val() + '&ToObjectID=' + ObjectID[1] + '&ItemID=' + $('#hidItemID').val() + '&ItemAmount=' + $('#hidItemAmountTo').val(),
async: false
}).responseText;
});
/************************************************/
$('div[id^="Item_"]').hover(
function(e) {
$(this).css("cursor", "pointer");
$(this).css("background-color", "blue");
},
//כשיוצאים מהשולחן DIVהעלמת ה
function() {
$(this).css("background-color", "white");
});
/************************************************/
//טיפול בבחירת פריט להוספה/הורדה מהחשבון
$('div[id^="Item_"]').click(
function() {
$('#imgLeftArrow').css("background-color", "yellow");
//הוספת הפריט לשדה הנסתר
$('#hidItemID').val($(this).children().html());
$('#hidItemName').val($(this).children().next().html());
$('#hidItemAmount').val($(this).children().next().next().html());
});
}
I am trying to display one page using the ajax call and put the result in the dialog...This is working great!!!
Next, if someone choses an item and press the left arrow pic, I am doing another ajax call that updates the database and returns the new HTML (using XML/SXL) and I am getting the right result from that also.
I am getting the first hover and click working great, but after I'm updating the data and getting the result the hover stops working and also the click event on the arrow. I think it is because i'm rendering the data inside the click event function but I don't know how to solve it.
If you are returning HTML and you expect to have click events and hover events happen on elements within the new returned html then you need to use the .live() jQuery keyword.
Update: As of jQuery 1.7, the .live() method is deprecated (and no longer exists starting in 1.9!). Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
I think I understand what you're trying to do...
If any of the HTML is in these statements:
$('#hidItemID').val($(this).children().html());
$('#hidItemName').val($(this).children().next().html());
$('#hidItemAmount').val($(this).children().next().next().html());
Contains jQuery, it will be rendered as plain HTML because they are being added to the DOM after event binding. What Griegs suggested willwork.
You'll need something similar to:
$('div[id^="Item_"]').live('hover', function(event) {
// do something on hover
});
$('#imgLeftArrow').live('click', function(event) {
// do something on click
});
$('#imgRightArrow').live('click', function(event) {
// do something on click
});
This way new elements will also trigger the handlers.