jQuery live() for removeAttr()? - jquery-selectors

I need to use removeAttr on elements that may be loaded via ajax. Is there a way to automatically do this, similar to the way you can bind events automatically with live()?
NOTE: I don't have control over the JavaScript libraries that are doing the ajax calls.

this creates a new event for all elements now and in the future that have your 'undesirable attribute', next we'll trigger it to fire and do its work.
$("mySelector").live("myRemoveAttrEvent", function(event){
$(this).removeAttr("myAttr");
});
on the successfull ajax call's function
// quick jQ ajax, the important part is on success
$("div").load("url", function(data, status, xhr){
..do work..
// this is the important part
$("mySelector").trigger("myRemoveAttrEvent");
});
if you do not have control over all the ajax, you have to piggy back on the user events that Cause the ajax to fire ... this is dirty:
//events you think cause the uncontrollable ajax to fire, e.g change
$("*").change()(function(event){
$("mySelector").trigger("myRemoveAttrEvent");
});

You can use complete option of the $.ajax request like this:
$.ajax({
......
complete:function(){
$('selector').removeAttr('attribute here');
}
});

What you're looking for is to handle this at the time those elements are loaded, which would be in the success callback for your AJAX call:
$.ajax({
// your details
success: function(html){
$('a', html).removeAttr('title');
$('body').append(html);
}
});
Update: If you don't have control of whatever is making the AJAX calls and it doesn't provide any hooks or callbacks, you are going to need to find another event to bind to in order to perform this action. Depending on how these elements are being inserted into the page and exactly what you're doing with them, you might be able to use delegate like this (just a guess):
$('body').delegate('p', 'load', function(){ /* remove attr */ });
I don't know of any events that are triggered when the DOM or a single element is modified. You can try load, but I don't think it gets called in the case of AJAX loaded and inserted elements.

Related

jquery triggerHandler doesn't work while trigger does

I am adding a click event to a checkbox which will show/hide additional fields depending on its checked status. I want the handler to fire on load to set up the initial page structure. For some reason triggerHandler is not working on the field. If I change it to 'trigger' the handler will fire, but the checkbox status will also change. Can you see what i've done wrong/why triggerHandler won't work?
$('body').on("click", "#hdimage", function(){
console.log('hd');
if(!$('#hdimage').is(':checked')){
$('.sd-dim').hide();
} else {
$('.sd-dim').show();
}
});
$('#hdimage').triggerHandler('click');
That happens (as described in the docs) because
Events created with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.
and since you use the delegated syntax of the .on() method which lets body handle the click event that occurs on the #hdimage element, that event never reaches the body..
Your Event is not bound to "#hdimage" its bound to 'body'
$(document).ready(function(){
$('#hdimage').on("click", function(){
alert("dostuff")
});
$('#hdimage').triggerHandler('click');
});

jQuery event handler .on() not working

I want to attach a event to dynamically created element class.So i used live function but it was not triggered. So checked live function reference ,there i red below notes
As of jQuery 1.7, the .live() method is deprecated. Use .on() to
attach event handlers. Users of older versions of jQuery should use
.delegate() in preference to .live().
so decide to use on function,But it still not working.The text field is already attached with jquery ui datpicker.On another element select i disabled that field.
jQuery("#from").attr('disabled','disabled')
.removeClass('date_picker_bg')
.removeClass('hasDatepicker')
.addClass('date_picker_disabled');
after disabled if i click i want to show alert or tooltip.so i tried this,but not working
jQuery(".date_picker_disabled").on("click", function(event){
alert('hi');
});
What may be the problem
I am using jquery 1.7.1 ( jquery-1.7.1.min.js)
The problem is that jQuery(".date_picker_disabled") finds elements with that class and binds to them. If elements don't have the class at the time the binding is made, the events will not be handled.
The on function allows you to get round this by handling them on another element when the event "bubbles up to" a parent element. In this instance, we could say the body element – there may be a more specific common parent you could choose.
jQuery(document.body).on('click', '.date_picker_disabled', function(event) {
alert('hi');
});
The event handler is now bound to the document.body element. All clicks that happen anywhere in the body are tested to see if they originated from an element matching the selector. If so, the handler is fired.
This is explained on the documentation for the on function. It is the same behaviour as was present in previous versions of jQuery with live and delegate functions.
Having taken another look at your code, you have disabled="disabled" set on your input element. click events are not fired on disabled elements.
This is tricky.
When your code runs, your element does not have .date_picker_disabled class so your jQuery(".date_picker_disabled") returns nothing and .on() is not called.
Apply .on() on the outer element and use the selector parameter:
// you can also do $(document).on()
$(<outer element>).on('click', '.date_picker_disabled', function() {
// do something
});
This will delegate the event to the <outer element>. The handler will only be executed if an element with class .date_picker_disabled has been clicked (second param).
From the documentation of .live():
Rewriting the .live() method in terms of its successors is
straightforward; these are templates for equivalent calls for all
three event attachment methods:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
So in your case, you would do:
$(document).on('click', '.date_picker_disabled', function(event){
alert('hi');
});
I was using jQuery 1.7.2 and tried all proposed methods:
Didn't work:
$(document.body).on('click', '.collapsible-toggle' function() {
console.log('clicked');
});
Didn't work:
$(document).on('click', '.collapsible-toggle' function() {
console.log('clicked');
});
None of them worked until I tried the following:
----- Worked! ----
$('body .collapsible-toggle').on('click', function() {
console.log('clicked');
});
Maybe you should do:
jQuery("body").on("click",".date_picker_disabled", function(event){
alert('hi');
});
in this way you attach the event handler to the bosy and specify to fire that event only when that selector ".date_picker_disabled" is matched.
BTW this is exactly how live() worked
try :
$(document.body).on( "click", ".date_picker_disabled", function() {
alert('hi');
});
document.body helps for dynamic html too.
Just chekc it out: .on not working on dynamic html

C# - Get textbox value and send to a javascript function

I have a simple form with three textboxes and a <canvas> on the same page and I have to validate these three fields and then get the values (if validated) sent to a javascript function to draw a picture and some text inside the <canvas> element. The form and textboxes wouldn't have to disappear after the values were submitted because the user could try out different results with different values. I've done other forms before but never tried using Ajax. I know I could use a client-side validation and get the textbox values with jQuery but I have more server-side code running that would make use of these three values. How can I do this?
in your controller, create a method to handle the results. I assume that this is for logging only, and does not need to actually return data.
public useResults(string value1, string value2)
{
// ... Do something with the results
return Json(true);
}
In your view, work out a way to construct the url to the above action. Perhaps in a hidden field;
#Html.Hidden("useResultsUrl", Url.Action("useResults", "controllerName"))
Then in your javascript, attach a click event to the button, as you probably have already (to trigger your javascript task) and add in an ajax call.
Note that the following uses JQuery, but you could use microsoft AJAX if you preferred;
$(function () {
$("#button").click(function() {
$.ajax({
url: $("input[name='useResultsUrl']").val(), // Get the url from the hidden field
type: "POST",
dataType: "JSON",
data: $("input[type='text']").serialize() // Get the value of the text inputs and serialise them.
});
});
// ... do other stuff
});
Your View can make an ajax call to the server using JQuery - either using JQuery.post
or JQuery.ajax - you give the Url of the controller action to the JQuery method, and it will handle the AJAX call for you.
Then, in your controller action, you return a JsonResult - which serialize the data for you into JSON format:
e.g. return Json( model );
Finally, implement a success function in the JQuery Ajax call in your view - this wil have the data returned by the controller available for you to do whatever you want with.

In jQuery Mobile, how do you target the element created using loadPage?

I load a "page" into the DOM using $.mobile.loadPage(). I then want to target the element created, but I haven't figured out how to do this. This is what I thought would work:
var toc = $.mobile.loadPage('toc.html');
toc.trigger('customevent');
The above does not work in part because toc is a "deferred promise object" rather than a good ol' jQuery DOM reference. Additionally, it does not work because the second line is triggered before loadPage finishes. Is there a way to fire a callback after loadPage?
Thanks!
If you know the id of the page being loaded then you can bind the 'pagecreate' event to that object with .live() like so:
$('#blah').live('pagecreate', function () {alert('created');});
This will fire after the page has been loaded into the dom.
I just was just able to figure this out, even if you don't have the id, here's an example of how i am performing an action (fadeIn) on the the inserted element....
$(document).bind('pageload',function(evt,data){
$(document).unbind('pageload');
$(data.page).fadeIn();
});
$.mobile.loadPage('mypage.html',{'pageContainer':$('#my_item')});
You can use pageshow in order to fire a callback when the page is loaded. Please refer to the jQuery Mobile Events API for more detail.
An example would be something like:
$('div').live('pageshow',function(event, ui){
...
});

How to call a function (non AJAX) after another function (non AJAX) finishes in Dojo?

This is not an AJAX request/response callback question...
I am building a grid using Dojo 1.5. I am trying to dojo.connect expand/contract buttons with a function. My problem is that the grid.startup() method seems to take a while after being called before the actual DOM nodes are created, so when I call dojo.query none of the DOM nodes I want to connect events and handlers to are present.
I have the grid being created inside an init() method, which is called by dojo.addOnLoad(). I have the connectExpandos() method connected to init() via dojo.connect("init", connectExpandos); This executes fine, but I need to setTimeout() within a while loop to wait for the grid.startup() to finish...
Anyone aware of a better way to do this? Perhaps a grid.startup() callback I can hook onto?
Another suggestion... it looks like the "startup" function, which is implemented in DataGrid's super class, _Grid (http://svn.dojotoolkit.org/src/dojox/trunk/grid/Grid.js), calls a function called render, which i believe is what actually render's the contents of the Grid. Subsequently, it looks like render calls a method "postrender" after it has finished rendering. Perhaps you could connect your method to the "postrender" method instead of "startup".
dojo.connect(grid, "postrender", function(){connectExpandos()})
I think the callback you were looking for was _onFetchComplete
dojo.connect(grid,'_onFetchComplete',function(event){
alert("hello data is loaded")
});
I think you can just connect an event to grid startup method
dojo.connect(grid, "startup", function(){connectExpandos()})
You could try creating the widget programatically (assuming you are not already), then just call your method after you call startup() (It seems odd to call startup() manually, but the example it shows in the source comments show calling grid.startup() manually).
<script type="text/javascript">
var grid = new dojox.grid.EnhancedGrid({plugins : {nestedSorting: true, dnd: true, indirectSelection: true,
menus:{headerMenu:"headerMenuId", rowMenu:"rowMenuId", cellMenu:"cellMenuId",selectedRegionMenu:"selectedRegionMenuId"}},
... }, dojo.byId('gridDiv'));
grid.startup();
connectExpandos();
</script>