jQuery not inserting attribute into the link - javascript

I have a link to slide down a div as follows.But initially this link has no onclick handler, which I am inserting using the jQuery code.
Show Div
Now the following is the jquery code
//id comes from a loop which runs from 1 to 15
$("#Link_"+id).attr('onclick','$(\'#Div_'+id+'\').slideToggle(\'slow\');');
$("#Link_"+id).attr('style','color:white;');
$("#Link_"+id).attr('value','0');
The last two lines are inserting attributes but the first line is not working and also I am not getting any error.I am using jQuery 1.4
EDIT
Now the surprise,I just by luck tried it,
the first line is working in jquery 1.9.Why?

You can't add a click handler like that, try this instead:
$("#Link_"+id).live('click', function(){
$('#Div_'+id+'').slideToggle('slow');
});

Try binding it this way:
$("#Link_"+id).on("click", function () {
$('#Div_'+id+).slideToggle('slow');
});
as you are using jquery 1.4. You would be needing live instead of on
$("#Link_"+id).live( "click", function() {
$('#Div_'+id+).slideToggle('slow');
});

I would recommend using .click() instead.
$("#Link_"+id).click(function(){
$('#Div_'+id).slideToggle('slow');
return false;
});
To answer the edit: jQuery 1.9 checks if you are trying to set an event handler and adds the handler instead of setting an attribute. jQuery 1.4 doesn't have such a check. (I looked at the source)

Related

click event not working jQuery

I am trying to handle the click event using jQuery
on upload success, I am creating the following using jQuery:
$("#uploadedImage").append( "<div class='img-wrap'>
<span class='deletePhoto'>×</span>
<img data-id='"+files[i]+"' src='"+asset_url+"uploads/ad_photo/"+files[i]+"'>
</div>
<span class='gap'></span>");
and for handling click event for the above created div's I have written this:
$('.img-wrap .deletePhoto').click(function() {
var id = $(this).closest('.img-wrap').find('img').data('id');
alert(id);
});
the above code is working properly and creates all div, but when I click on the deletePhoto span. no jQuery alert is showing.
Any help or suggestion would be a great help.
Thanks in advance
delegate the event and change as suggested:
$("#uploadedImage").on('click', '.deletePhoto', function() {
You have to delegate your event to the closest static parent #uploadedImage in your case which is available on the page load like the container which holds the newly appended div and image.
although $(document) and $(document.body) are always available to delegate the event.
It is better to use on() when you create new element after DOM has been loaded.
$(document).on('click', '.img-wrap .deletePhoto', function() {
});
You are creating your element dynamically that is why you would need .live()
but this method is deprecated in newer version.
if you want to use jquery 1.10 or above you need to call your actions in this way:
$(document).on('click','element',function(){
`your code goes in here`
})
try this:
$(".img-wrap .deletePhoto").on('click', function() {
});
You can change a little in your code.
$(".deletePhoto").off("click").on("click",function(){
//Your Code here
});
First check in debugging mode that you get length when your code is going to bind click event and another thing bind event must written after that element is appended.
And Also check css of your element (height and width) on which you are clicking and yes
$(document).on('click','Your Element',function(){
//your code goes in here
});
Will works fine
use delegate:
$('#uploadedImage').on('click','.img-wrap .deletePhoto',function() {
var id = $(this).closest('.img-wrap').find('img').data('id');
alert(id);
});
see details delegate and .on here

Jquery event bubbling when .on event is within a nested function

I have this code in the body onload event:
$.each(["#tbl_p2", "#tbl_p5", "#tbl_ukalk"], function(index,value){
$("tbody tr:not(:last)", value).find("input[type='text']:visible:last").on("blur", this, function(){
$("tbody tr:last input[type='text']:first", value).focus()
})
})
The mentioned tables (tbl_p2, tbl_p5 and tbl_ukalk) are all added dynamically at some point and they consists of several lines with several text inputs at each line. The intention of the code is to focus() the first input of the last line whenever the the last input of whichever line is blurred.
It works when applied through the console, but not via onload, so I know it has something to do with bubbling. I've tried to add "document" like this...
$.each(["#tbl_p2", "#tbl_p5", "#tbl_ukalk"], function(index,value){
$("document tbody tr:not(:last)", value).find("input[type='text']:visible:last").on("blur", this, function(){
$("tbody tr:last input[type='text']:first", value).focus()
})
})
...to bubble far enough out, but that won't work neither in console or onload - I'm assuming beacuse "document" isn't part of the given context in $.each().
I've also tried to do $.each(["document #tbl_p2", ...]) but that doesn't work either.
Edit: Added jsfiddle with working code. If the tables were added dynamically, it wouldn't work.
Edit II: Updated jsfiddle with dynamically added table, which serves to show that the event listener doesn't update to the new table element.
Edit III: 100% working jsfiddle, many thanks to #Rob Schmuecker (see accepted answer)
I think this is to do with event delegation since the tables aren't loaded by the time you've called onload?
Have a look here http://api.jquery.com/on/ about delegating your events.
You may have to reformat your code slightly to get it to work properly.
Or alternatively call your code only when the tables have actually been loaded into the DOM such as in the success callback of an ajax request or similar.
EDIT:
Here is a correct working fiddle http://jsfiddle.net/7UTBQ/3/
and here is the correct working javascript
JS:
$(document).on("blur", "table tr:not(tr:last-child) td:last-child input[type='text']:visible", function (event) {
console.log('blur');
$("tr:last input[type='text']:first", $(event.target).parents('table').get(0)).focus();
});
try this
$.each(["#tbl_p2", "#tbl_p5", "#tbl_ukalk"], function(index,value){
$("document tbody tr:not(:last) "+value).find("input[type='text']:visible:last").on("blur", this, function(){
$("tbody tr:last input[type='text']:first "+value).focus()
})
})
Not tested by my side you can try..

Re-enable links disabled with disable_with

How can I manually re-enable links (not form elements) that get disabled with Rails' disable_with feature?
The call to reenable links is slightly different than form elements. It actually binds a handler to the click event that stops anything else from happening. I was able to figure this out by investigating how the jquery-ujs library.
To reverse this effect, simply use the enableElement method on your jQuery object:
$.rails.enableElement($('a[data-disable-with]'));
With Turbolinks, it also helps to watch for the 'page:change' event instead of window.unload:
$(document).on('page:change', function() {
$.rails.enableElement($('a[data-disable-with]'));
});
A solution I found here:
$(window).unload(function() {
$.rails.enableFormElements($($.rails.formSubmitSelector));
});
Rails has updated their javascript to no longer use jQuery.
You can now re-enable elements with the following (assuming you are still using jQuery):
var selectors = [Rails.linkDisableSelector, Rails.formEnableSelector].join(', ');
$(selectors).each(function() {
Rails.enableElement(this);
})
Hey its quite simple you just need to find button and do
$button = $('#someId')
$.rails.enableElement($button)
$button.removeAttr('disabled')
Based on #DGM solution I ended up with the following code:
$.rails.enableFormElements($disabled_button);
Where:
$disabled_button is the jQuery object for the button disabled by data-disable-with which could be selected like this:
$disabled_button = $('[data-disable-with]');
OK I found this interesting work around (apparently the problem is only in FF)
set :autocomplete => 'off' and now it works. Or one of the other answer might work as well.
ref: https://github.com/rails/jquery-ujs/issues/357
You can use jQuery to remove the data-disable-with attribute that Rails adds to the button:
$('#disabledbutton').removeAttr('data-disable-with');

jquery related question

i am modifying the inner html through javascript, and the inner html involves a button
but when i put in the jquery code to run on the button click event it fails to do so ..
sorry but im a newb when it comes to javascript
content im adding into the html ..
function add()
{
var val=document.getElementById("ans").value;
document.getElementById("answers").innerHTML+="<tr><td>"+val+"<br/><p align=\"right\"><button class=\"replyb\">replies</button></p>"+"</td></tr>";
document.getElementById("ans").value="";
}
jquery code ...
enter code here
At a guess, because we don't have your jQuery, I would say you need to use .live() instead of .click() when you change the HTML the button will be NEW to the DOM.
When you apply your jQuery code, it adds any calls like .click() to any DOM item, when the page loads. So any NEW element doesn't have a .click() handler added to them.
Do solve this, you can change your .click():
$('#someitem').click(function() {
.....
});
To something like this:
$('#someitem').live('click', function() {
.....
}
Add the following in your page at some place and it will handle clicks to all .replyb buttons whether you add them with javascript at any time, or not.
$(function(){
$('button.replyb').live('click', function(){
alert('clicked on button');
});
});
have a look at jquery .live() method

How do I keep events elements added through a ajax call in jQuery "active"

I'm placing content on my page through an ajax (post) request like so:
$("input#ViewMore").click(function() {
var data = { before: oldestDate, threadId: 1 };
$.post("/Message/More", data,function(html) {
$('tbody#posts').prepend(html);
return false;
},
"html");
return false;
});
with the html coming back looking something like:
<div id="comment">Message output Quote</div>
This is all working fine and dandy, everything appears as it should, no problems.
The problem occurs when I have an event hooked into the "quote" anchor that has been added through the ajax call. Specifically, a jQuery event on that anchor does not fire. Why?
For instance:
$("#quote).click(function() { ... });
Does nothing. Acts like there is no event on it. I know it is working on other anchors on the page that were not added through a ajax request, so there is not a code error there, plus if I refresh the page it will then fire correctly. Is there some reason that this is happening, do I need someway to reinitialize that event on the anchor tag somehow? Any ideas?
Working with jQuery 1.3.1 (didn't work with 1.2.6 either) so I believe it is my implementation not code itself.
You can use Events/live of jQuery 1.3, live will bind a handler to an event for all current - and future - matched elements.
When the new content is added to the page with Ajax you have to re-register all the events to those new elements.
Changed to
$('#quote').live("click", function() { ... }
and
$("input#ViewMore").live("click", function() { ... }
Doesn't seem to work
CMS's answer helped, but here's how it ended up:
The view more button event remained the same as it was outside of the AJAH request that added it:
$("input#ViewMore").click( function() { ... }
Elements that had events that were being added in and out of the AJAH request needed to use the live method:
$('#quote').live("click", function() { ... }
Works like a charm!

Categories