jquery problem #.# - javascript

$('#save').click(
function(){
alert('run');
update_form('get_form','main_content',true);
}
);
hi,i got a problem in my program..... please help me T.T.
above function is not run. i think the clue should be here.
$.ajax({
......
$('#' + divtoupdate).html("<input type='submit' id='save' name='save' value='Save'/>");
})
all ajax part is ok, i think is because dom problem?,
the click() is created before i run the ajax.(i have the action before i got the input) is this causing click function malfunction. any solution for this problem ^^ thx

You should use jQuery live

Yes..for the click function on 'save' button to work...it should be present when page is loaded...try running click after ajax function..it should work fine then..
Even Live function will work --- It will take care of element even if it is added in future.
$('#Save').live('click',function(){
//ur code here
});
But Live will not work on older browsers.

You need to use $.live to workout event handling on elements added dynamically.
$('#save').live('click', function(){ ... });

I think what you are trying to say is that the first bit of code won't work because the second bit of code hasn't run yet. This second bit of code adds the HTML which the first bit works upon.
In which case, try the live() function instead of click()

You need to add the click handler after the object is created. You could just add your existing handler code to the ajax success, after the line where you create the #save element.

Yeap, try putting your $('#save').click inside your ajax callback function.
$.ajax({
......
$('#' + divtoupdate).html("<input type='submit' id='save' name='save' value='Save'/>");
$('#save').click(
function(){
alert('run');
update_form('get_form','main_content',true);
}
);
})

try out this...add the function after you add the actual element...
$.ajax({
......
$('#' + divtoupdate).html("<input type='submit' id='save' name='save' value='Save'/>");
$('#save').click(
function(){
alert('run');
update_form('get_form','main_content',true);
}
);
})

$(document).ready(function() {
var waterVolume
function initialFill(){
waterVolume = Math.floor(Math.random() * (150000 - 50000 + 1)) + 50000
initialWidth = $('.resizable_tank').width()
initialHeight = $('.resizable_tank').height()
stabilizeWaterPipe(initialWidth,initialHeight)
}
function stabilizeWaterPipe(currentWidth,currentHeight) {
stableHeight = $('.resizable_tank_pipe').offset().top + $('.resizable_tank_pipe').height() + 8
$('.stable_tank_pipe').css({height: (stableHeight-400)+"px", bottom: "-"+(stableHeight-400)+"px"})
stabilizeCalc(currentWidth,currentHeight)
}
function stabilizeCalc(currentWidth,currentHeight) {
stableTankWidth = $('.stable_tank').width()
stableTankHeight = $('.stable_tank').height()
increasedHeight = parseFloat(currentHeight - stableTankHeight)
// im getting problem here with filling and make equal levels of water in both the cylinders would u pls help me with some code .
}
$('.resizable_tank').resizable({
handles: 'e,s,se',
maxWidth: 800,
minWidth: 180,
minHeight: 400,
resize: function(event, ui) {
var currentWidth = ui.size.width;
var currentHeight = ui.size.height;
stabilizeWaterPipe(currentWidth,currentHeight)
}
})
initialFill()
});

Related

Bind an event on a jquery generated element

My code is like this:
$('.flag-icon-dz').click(function() {
var lang = 'Arab';
var $frame = $('.goog-te-menu-frame:first');
if (!$frame.size()) {
console.log("Error: Could not find Google translate frame.");
return false;
}
$frame.contents().find('.goog-te-menu2-item span.text:contains(' + lang + ')').get(0).click();
$("li.ql-item.linkid188546").after("<li class='ql-item linkid18854777 closegoogle'><a href='#' class='btn-primary' target='_self'><i class='icon closegoogle ls-lang-frr' aria-hidden='true'></i></a></li>").fadeIn(500);
$('li.ql-item.linkid188546').fadeOut(500);
return false;
});
$('.closegoogle').click(function() {
$('.skiptranslate').contents().find('.goog-close-link > img').click();
$('li.ql-item.linkid18854777').fadeOut('fast').remove();
$('li.ql-item.linkid188546').fadeIn(500);
});
The first function works great, but the second doesn't. I realize that if I copy/paste the second function in the console after the first one, it works too.
I tried a few solutions (callback / setTimeout / jquery deferred / jquery .when method...) I didn't try promise but I don't think I have to in my context. Maybe I didn't write these solutions good enough.
I finally try to put my event (click) directly the .before() which create my new element like this :
$('.flag-icon-dz').click(function() {
var lang = 'Arab';
var $frame = $('.goog-te-menu-frame:first');
if (!$frame.size()) {
console.log("Error: Could not find Google translate frame.");
return false;
}
$frame.contents().find('.goog-te-menu2-item span.text:contains(' + lang + ')').get(0).click();
$("li.ql-item.linkid188546").after("<li class='ql-item linkid18854777 closegoogle'><a href='#' class='btn-primary' target='_self'><i class='icon closegoogle ls-lang-frr' aria-hidden='true'></i></a></li>").fadeIn(500).click(function() {
$('.skiptranslate').contents().find('.goog-close-link > img').click();
$('li.ql-item.linkid18854777').fadeOut('fast').remove();
$('li.ql-item.linkid188546').fadeIn(500);
});
$('li.ql-item.linkid188546').fadeOut(500);
return false;
});
But it doesn't work either.
Thanks for the help.
EDIT :
I finally found a kind of solution for my second click event (which isn't the best solution but i works) :
window.setInterval(function(){$('.closegoogle').on("click",function(){
$('.skiptranslate').contents().find('.goog-close-link > img').click();
$('li.ql-item.linkid18854777').fadeOut('fast').remove();
$('li.ql-item.linkid188546').fadeIn(500);
}); }, 1000);
Thanks.
You need to use a delegated bind as the element does not exist before you try your binding:
$('#parent-element-of-closegoogle').on('click', '.closegoogle', function() {
$('.skiptranslate').contents().find('.goog-close-link > img').click();
$('li.ql-item.linkid18854777').fadeOut('fast').remove();
$('li.ql-item.linkid188546').fadeIn(500);
});
Please note that the #parent-element-of-closegoogle needs to be an element that already exists when you do the binding - this can be $(document) if you hjave no other element to bind to

$anchorScroll is working on second click, when I have called in other submit function

I am still facing this issue. My issue little a bit different
I am calling my $anchorScroll function in other event. When form is being submitted. It is working on second click same as above. I have also tried earlier anwsered solution, but no luck :(
$scope.scrollTo = function(element) {
var old = $location.hash();
$location.hash(element);
$anchorScroll();
$( 'html, body').animate({
scrollTop: $(element).offset().top
}, 1000);
$location.hash(old);
};
And I am calling it in another function, which is submitting the form.
$scope.saveProfile = function (profile) {
$log.debug("now the profile is " + JSON.stringify(profile));
dataFactory.persistChange("profiles",profile,$scope,postSuccessUpdate);
$scope.scrollTo( "#error ");
}
And here is my anchor
<div ng-class="statusDisplayClass" ng-show="messages" id="error">
Here it will be displayed
</div>
Please help me on this. Where I am lacking.
Could you change your $scope.scrollTo( "#error "); to $location.hash('error');
$anchorScroll();.
It should look like below:
$scope.saveProfile = function (profile) {
$log.debug("now the profile is " + JSON.stringify(profile));
dataFactory.persistChange("profiles",profile,$scope,postSuccessUpdate);
$location.hash('error');
$anchorScroll();
}
I am not sure if that's work because in my environment it works fine.

JQuery code working properly in jsfiddle but not in browser even with $(window).load(function())

So I'm trying to make a search using a dropdown list, which will show/hide some checkboxes depending on the chosen answer. The problem is that it works perfectly on jsfiddle.net but refuses to load properly on my local machine. I saw a similar post and said something about adding $(window).load(function()) before the rest of the script, but even then it refused to work. I might be doing something wrong so any help is appreciated.
The link for jsfiddle is this: http://jsfiddle.net/CDyZf/66/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
$(window).load(function());
$('.drop-down-show-hide').hide();
$('#dropDown').change(function () {
$(this).find("option").each(function () {
$('#' + this.value).hide();
});
$('#' + this.value).show();
});
</script>
The argument of load() needs to be a function.
load(function()) would pass it the return value of calling a function called function, if function wasn't a reserved word making it a error.
function init() {
$('.drop-down-show-hide').hide();
$('#dropDown').change(function () {
$(this).find("option").each(function () {
$('#' + this.value).hide();
});
$('#' + this.value).show();
}
$(window).load( init );

Linking button to jQuery through service

I have a small problem that should be very easy to overcome. For some reason I cant work this out. So the problem is I cannot get a button to link to some jquery. My set-up is as follows (showing the relevant code):
Default.aspx
jQuery:
function getContent() {
var data = {
numberID: 1
};
$.jsonAspNet("ContentService.asmx", "GetContent", data,
function (result) {
$('#content').html(result);
});
}
jQuery(document).ready(function () {
getContent();
});
HTML:
<div id="content"></div>
ContentService.vb
<WebMethod()> _
Public Function GetContent(number As Integer) As String
Dim sb = New StringBuilder
sb.AppendLine("<table>")
sb.AppendLine("<tr>")
sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Number</td>")
sb.AppendLine("</tr>")
sb.AppendLine("<tr>")
sb.AppendLine("<td>" & number & "</td>")
sb.AppendLine("<td><a href='#' id='test' class='fg-button ui-state-default ui-corner-all'><img src='" & Context.Request.ApplicationPath & "/images/spacer.gif' class='ui-icon ui-icon-pencil' /></a></td>")
sb.AppendLine("</tr>")
sb.AppendLine("</table>")
Return sb.ToString
End Function
So that's the basics of what I have everything works but I'm not sure how to get the a button (id='test') to get linked to some jQuery. I want it to be pressed and bring up a popup.
I have tried to put the jQuery on default.aspx but this doesn't seem to work unless the button is place in the HTML on that page.
$('#test').unbind('click').click(function () {
alert('Working');
});
I'm sure this is easy to do, but I have been trying for a while and cannot seem to get it to work.
Is the problem that you're trying to bind to the element that ISN'T in existance yet?
are you calling the $('#test').unbind('click').click(function () {
alert('Working');
}); BEFORE the service has returned?
$('#test').on('click', function () {
alert('Working');
});
This will bind the event to the '#test' element once it has been inserted in to the DOM.
As you load the content via ajax, you have to bind to $('#content'). Like this:
$(function () {
$('#content').on('click', '#test', function () {
e.preventDefault(); // if a default action is not needed needed
alert('Working');
});
});
I guess this is about not preventing the default behaviour of the A href tag. Now it will probably link to '#' instead of firing the onclick event.
$('#test').on('click', function (e) {
alert('Working');
e.preventDefault();
});
You could try to wrap this in a document ready, or eventually use the .on binder from jQuery, since it's dynamic content.
Solved
It was a very small thing that caused this. The code to fix this problem is as follows:
$('#test').unbind('click').click(test);
This needed to go inside the function with the json so:
function getContent() {
var data = {
numberID: 1
};
$.jsonAspNet("ContentService.asmx", "GetContent", data,
function (result) {
$('#content').html(result);
$('#test').unbind('click').click(test);
});
}
Thank you to everyone that has tried to help me.

jQuery elements inside a jQuery dialog stop working after ajax call

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

Categories