jQuery elements inside a jQuery dialog stop working after ajax call - javascript

<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.

Related

Javascript alert not working for a particular function

I am passing a table with a button in drupal 7 and trying to print the values but iam not getting any alert
$(document).ready(function() {
$('#edit-title-poc').change(function() {
alert('sdsd'); //**this alert works**
var poc_valueasdasd = $("#edit-title-poc option").filter(":selected").val();
$.ajax({
url: Drupal.settings.basePath + 'ajaxpocsdas3',
data: {
pocdasd: poc_valueasdasd
},
success: function(aasdsabc) {
//data: value returned from server
$('#msg-diasdsadsad').html(aasdsabc);
}
});
});
$('#poc3modulepdf-generator').click(function() {
alert("Handler for .click() called."); //this alert is not working
});
});
This is the screen shot
Use
$(document).on('click','#poc3modulepdf-generator',function(){
alert('clicked')
})
The reason why your code is not working is because you are binding an event to the element which is not yet created.
Using $(document).on('click','#poc3modulepdf-generator') will bind the event to document. This is event delegation. For more details on event delegation see here
I hope this will help.

jQuery .bind('show') not working appropriately when element is shown via jQuery

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({
...
});
});

jQuery event fires once, then never again

I've been wrestling with a simple JQuery event handler for hours.
My event handler fires exactly once, when the page loads, and never again no matter the event or the interaction with the select box.
When deferred, the alert (when I have one) shows the first select option. When not, the alert is blank.
All I want is for the select box to load from AJAX and for a user choice to trigger another AJAX call.
HTML:
<select id="connection" name="Connection"></select>
<div id="testme" style="background: #CCC; width:100%; height:50px;position:relative;color:red">testing</div>
Javascript:
$(document).ready(function () {
// Event handler. Tried as a separate function and as a parameter to $.on(...)
function connectionSelected() {
var str = $('#connection option:selected').text();
alert(str);
$("#testme").text(str);
}
var $connectionSelect = $('#connection');
//$connectionSelect.selectmenu(); // Tried enabling/disabling
// Tried this and all JS code inside and outside of $(document).ready(...)
$.when(
$.ajax({
dataType: "JSON",
url: '#Url.Content("~/API/ConnectionHint")', // The AJAX call (using ASP Razor) works fine
success: function(data) {
// This function is always called and works
var items = [];
$.each(data, function(key, val) {
items.push("<option value='" + key + "'>" + val + "</option>");
});
$connectionSelect.append(items.join(""));
// Tried setting up the event handler here
},
error: function() {
$connectionSelect.html('<option id="-1">none available</option>');
}
})
).then(function() {
//$("#connection option").blur(connectionSelected()).change();
$("#connection").on("change", connectionSelected());
});
});
Tried dozens of variations of the event handler, several events, inside and outside of a deferred.done and deferred.then, etc.. E.g.:
$connectionSelect.selectmenu({
change: function (event, data) {
$('#connection').change(function () {
var str = "";
$('#connection').each(function () {
str += $(this).text() + "<br>";
});
$("#testme").text(str);
});
}
});
I usually write back-end code and am familiar only with portions of JQuery, and this is driving me crazy. I've looked more than 30 related question on SO and elsewhere, e.g.
Jquery event fires once
Jquery .change() function not working with dynamically populated SELECT list
http://jqueryui.com/selectmenu/#product-selection
Any ideas are appreciated.
Instead of
$("#connection").on("change", connectionSelected());
try
$("#connection").on("change", connectionSelected);
Note that in the second one I'm passing your function handler by reference, instead of invoking it.

Call jquery function when one function completes

So I have a jquery click function assigned to an on/off toggle. Very simple script:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
$this.find('.slider').toggleClass('active');
});
We have two versions of this toggle. One toggles instantly when clicked and then we submit the value when clicking next(aka submit).
Our other one calls a jquery ajax function that toggles on success and upon success if it is a specific message code that is defined on the backend.
jQuery.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: {'requestType': requestType},
success: function(message) {
if(message.STATUS=='2000'){
if(currentButtonClicked=='dashboardChargingButton'){
if($('#dashboardChargingButton').html()==startCharge)
$('#dashboardChargingButton').html(stopCharge);
else
$('#dashboardChargingButton').html(startCharge);
}
if(currentButtonClicked=='invokeChargingButton'){
$( "#invokeChargingButton .slider" ).toggleClass( 'active');
}
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + " - " + xhr.statusText);
}
});
}
As you can see I have to toggle the class again using the same code but with direct targeting.
The on off toggles of this type have an onclick inside the actual html calling the function that handles this ajax.
My goal is to have my first set of code the one that targets the element and toggles the class to do all of this, but dynamically to where we don't have to call a function everytime.
Conceptually what I thought is:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
if (!$this.attr('onclick')) {
$this.find('.slider').toggleClass('active');
} else {
var clickFunction = $this.attr('onclick');
call the clickFunction
if (clickfunction = true) {
$this.find('.slider').toggleClass('active');
}
}
});
What this would do is grab the onclick, but not call it until I specify. And inside the ajax request instead of toggling I would just return true.
This might not be the best method. I am just trying to ecapsulate everything to limit the amount of code as well as make all the dom changes for those elements in one spot for any potential defects.
Here is a link to a basic fiddle of the on/off toggle.
Fiddle
I hope I explained everything in good enough detail.

How do I pass the deleted row name from a grid in jQuery to controller(server-side) with ajax call

I have added a row to a grid in jQuery success function, like this(edited adding Rob and Fleix comments):
$(function() {
$('#MyGrid').delegate('a.remove', 'click', function() {
alert("del");
// e.preventDefault();
jQuery.ajax(
{
type: "POST",
url: "Upload/Remove",
data: "removefile=" + stringhtml// error console shows it as undefined
});
$(this).closest('tr').remove();
});
$("#uploadForm").ajaxForm({
iframe: true,
dataType: "xml",
url: "Upload/Index",
success: function(result) {
('#MyGrid tbody').append('<tr><td> ' + stringhtml+ ' </td><td><a href="#"
class="remove">Remove</a></td></tr>');
});
});
the ajax call is not making for remove click ,but is hitting once page is loaded. How to make the ajax call for remove click, with passing the stringhtml?
Could you guys help me out!
thanking you,
michaeld
Bind to the click event of the remove links
$('#MyGrid').delegate('a.remove', 'click', function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
Change your row append code to
$('#MyGrid tbody').append('<tr><td> ' + stringhtml+ ' </td><td>Remove</td></tr>');
First, update your "Remove" link so that it is like:
Remove
Then implement your remove() function like this:
function remove(node) {
node.parentNode.parentNode.removeChild(node.parentNode);
//equivalent: $('#MyGrid tbody')[0].removeChild(node.parentNode);
}
Here's an example: http://jsfiddle.net/nNde4/5/
First of all, avoid using inline onclick attributes. Instead use $(selector).bind('click', function(e){}); or $(selector).click(function(e){});. In your case, actually using live() would make more sense, since you don't have to attach every event over and over. So using the following should work:
$('#MyGrid a').live('click', function(e){
$(e.target).parent().parent().remove();
});
Also note that you don't have to call this every time you add a row. Call this only once when the tabel is created (on load etc) and it should work just fine.

Categories