.click function not working for me - javascript

I have lots of jquery functions in my script but a particular one is not working, this is my function
$('#delete').click(function() {
var id = $(this).val();
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=delete&id=' + id ,
success: function(response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$(this).parent('tr').slideUp('500').empty();
}
});
});
a similar function like this is working
<!-- WORKING FUNCTION -->
$('#UpdateAll').click(function() {
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=updateAll',
success: function(response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$('#table').slideUp('1000').load('data.php #table', function() {
$(this).hide().appendTo('#divContainer').slideDown('1000');
});
}
});
});
I checked with firebug, the console doesnt show any errors, i checked html source the values are loading correct, i checked my php file 5times it is correct can't figure out the problem. Please Help.

I struggled with the EXACT SAME PROBLEM for 6hr straight! the solution was to use jquery 'live'.
And that is it.
$('#submit').live('click',function(){
...code...
});

With the first one, I'd put a quick and nasty alert() within the click anonymous function, to ensure that it is being fired. Eliminate reasons why it may not be working. Also, try using Live HTTP headers or Firebug's console to see if the AJAX request is being sent.
If the click is not being fired, see if you have the selector correct. I often do this (quite nasty)
var testSelector = 'p:first ul li:last';
$(testSelector).css( { border: '1px solid red' } );
It won't always be visible, but if you see style="border: 1px solid red"` in the generated markup, you know your selector is on the ball.
Perhaps you have another click that is overwriting it? Try using
$('#delete').bind('click', function() {
// do it
});

I just had the same problem with a quick example I was working on. The solution was to put the click inside $(document).ready. I was trying to use my element before it was actually ready to be used.
It's basic JavaScript to wait until the DOM is ready before you try to use an element, but... for whatever reason I forgot to do that, so maybe the same happened to you.

$(document).on('click', '#selector', function(){
// do something
});
jQuery 1.7+ has depreciated .live() and now uses .on() instead :)

I don't know if this applies in your context, but if you have parts of the page that are getting loaded by AJAX then you'll need to bind the click handlers after that content is loaded, meaning a $(document).ready isn't going to work. I've run into this problem a number of times, where certain events will fire fine until parts of the page are reloaded, then all the sudden the events seem to stop firing.

Just use your .click with $(document).ready(function(){ ... }); because you are trying to apply the click event on a non-existent element.

1) just before the last }); you should add return false;
2) Are you sure that #delete exists? Also, are you sure is UNIQUE?

This is a long shot, but it's good to be aware of.
http://code.google.com/p/fbug/issues/detail?id=1948
May not be an issue if you're not on Firefox 3.5.

Instead of id=delete i changed it to class=delete in html and in js ('.delete') and it is working fine now but when again tried with id it doesnt work.
Thank You all for Help, i dont have any problem whether it is id or class just the function works now.

There is few things you can do:
like Elmo Gallen and Shooz Eh suggested, put your code in $(document).ready(function(){...});
code your $('#delete').click(function(){...}); event handling AFTER your <button> tag,
use $('#submit').live('click',function(){...}); like Parikshit Tiwari suggested.
Everyone of these should work ok.
EDIT: oops, didn't see that this was asked '09 :D

I think you must use .on() function for dynamically code run in jQuery like this:
$(document).on("click","#delete",function(){ });

Related

jQuery doesn't like .on and .append?

I have a weird problem.
I'm currently working on loading posts using PHP, AJAX and MySQL. The code structure itself looks like this:
My code structure
--- main.js ---
$(window).load(function(){
initAjax();
});
--- ajax.js ---
function initAjax(){
// Toggles a navigation
$(document).on('click', '.btn.open', function(){
... toggles a window ...
});
// Add new posts
$(document).on('click', '.btn.refresh', function(){
$.ajax({
... ajax stuff ...,
success: function(html){
// Show new posts
$('.post_container').prepend(html);
}
});
});
}
So what is the problem?
When I append new posts they'll show up, but I am not able to click .btn.open anymore - Shouldn't 'on()' fix this? When I go to the Google Chrome console.
Does somebody know a potential way to solve the problem?
Edit:
The appended posts are the same as the default loaded posts!
'.btn.open' exists (div with class="btn open")
I am using jQuery v2.0.3 (so .on should work!, .live and .delegate were replaced by .on!)
Removed an error message that was created by a corrupted Chrome extention = No change.
Created a .gif showing the problem in action: http://d.pr/i/cJB3
FIXED! #cmorrissey found a small solution by replacing $(document) with $('body')
BUT
This fix doesn't seem to be a perfect solution since $(document) normally has to work! Since I want clean code, I am totally going to try out #Potherca's Short, Self Contained, Correct, Example method and probably I'll find the solution this way. Thanks
You need to use 'body' or document.body instead of document.
$('body').on('click', '.btn.refresh', function(){
$.ajax({
... ajax stuff ...,
success: function(html){
// Show new posts
$('.post_container').prepend(html);
}
});
});
Reason: The addition of content to the body doesn't bubble up to the document level (http://bugs.jquery.com/ticket/11621), it looks like you can also use window

Unable to find click event

Here is my JQuery Code:
$(function () {
$('[id*=clickbtn]').click(function () {
var url = "WindowPages/EditorControl.aspx?controlName=" + this.name;
oWnd.setUrl(url);
oWnd.show();
});
});
Now the problem is, i have 4 to 5 buttons whose id contains 'clickbtn' when i click the any one of them for first time it works well. But it does not works for second click, any help why is this happening?
[EDIT]:
I tried putting the JQuery on page and it worked.. But wnt to know why it does not work on when i put the same on .JS file?
Yes, the result of your event handlers depends very much on the content of your event handlers. If you'd like to share with us the rest of the code we might be able to help. For now the answer is: working as intended
jsFiddle
If your clicks only work on the first try, then I can assure you that it is only the missing code which is to blame. Provide the contents of oWnd.setUrl and oWnd.show and we might be able to help.
Your wildcard selector is wrong. It should be
$("[id$=clickbtn]")
Try this:
$('input[ID*="Button"]')
OR
First set class="btn" to all buttons you want to do this action then
$(function() {
$('.btn').click(function() {
var url = "WindowPages/EditorControl.aspx?controlName=" + this.name;
oWnd.setUrl(url);
oWnd.show();
});
});

Ajax fires only once,and the javascript file is loaded only once

Basically, I am trying to load the html and JavaScript file for each subpage on my website with ajax. However, the JavaScript file only loads for the first subpage that is clicked on. If I click on the next subpage, only the html document for that loads, but the javascript does not. This is from looking at the firebug console: Clicking on about first, then clicking on contact:
GET http:..../about.html?t=0.19504348425731444
GET http:..../about.js?t=0.8286968088896364
GET http:..../contact.html?t=0.8467537141462976
(!!!NO GET FOR contact.js!!!)
Anyways, I tried using live() to bind the click event but it still doesn't work.Here's the relevant snippets of my code:
$('.subpage').live('click',function(){
$('#main').css({'cursor':'crosshair'});
navsubpage = true;
subpage = $(this).attr('id');
$('.subpage').each(function(index) {
$('#'+$(this).attr('id')).fadeOut('500');
$('#'+$(this).attr('id')+'select').fadeOut('500');
});
$('#'+subpage+'h').css({'background-color':'#000','display':'block'});
$('#'+subpage+'h').animate({'width':'375px','top':'120px','left':'100px','font-size':'400%'},'500');
subtop = $('#'+subpage+'h').css('top');
subleft = $('#'+subpage+'h').css('left');
$('#pane').css({'border-left-width':'0px'});
$('#nav').css({'background':'url("images/'+$(this).attr('id')+'.jpg") no-repeat 0px 0px'});
$('#nav').animate({'left':'0px'},'4000','swing',function(){
$('#reload').show().delay(500).queue(function(){
alert("made it");
$.ajax({
url: subpage+".js?t=" + Math.random(),
dataType: 'script',
type: 'get',
});
});
});
reload(subpage);
});
$('#main').click(function(){
if(navsubpage==true){
$('#main').css({'cursor':'auto'});
$('#reload').hide();
$('#pane').css({'border-left-width':'10px'});
$('#'+subpage+'h').animate({'width':'150px','top':subtop,'left':subleft,'font-size':'200%'},'2000',function(){
$('#'+subpage+'h').css({'display':'none'})});
$('#nav').animate({'left':'415px'},'3000','swing', function(){
$('.subpage').each(function(index) {
$('#'+$(this).attr('id')).fadeIn('3000');
$('#'+$(this).attr('id')+'select').fadeIn('3000');
});});
navsubpage = false;
}
});
the reload function loads the html and is working correctly.
I am really new to ajax, javascript...etc. If any of you can help me out, that'll be great.
It's confusing that you have both the "?t=" + Math.random() combined with cache: true.
The practice of appending a timestamp to a URL is a common method to prevent caching, but then you explicitly tell it that you want it to cache. You might try removing the cache: true option, as it looks to be totally superfluous and can only cause problems (the likes of which would resemble what you're describing here).
I would reccomend trying out a jQuery ajax shortcut function $.get()
It is farly simple and might cut out a lot of uneccesary options you are setting using the full $.ajax() function
Thanks for the help guys - in the end I just decided to not mess with the queue stuff. I still don't understand why it works, but I just took out the ajax and placed it outside of $('#reload').show().delay(500).queue(function(){, eliminating the delay and queue stuff and making the ajax a separate snippet of code. now it loads correctly.

jQuery - Click on X, grab the NAME, then use that to show a related element

Here's what's happening.
My page loads. Then jQuery loads a feed which is injected into a contentCol div...
in that feed is:
Comment
There is also:
<div class="storyItemComments" id="storyItemComments_66" style="display:none;">....
For some reason this is not working:
$(".commentWrite").live("click",function(){
cmt2open = $(this).attr('name');
$("#" + cmt2open).show();
return false;
});
Any ideas? The only thing I can think of is that it has something to do with the fact that I am using jQuery AJAX to load in the content which the LIVE statement above is referencing....
thanks
on most occasions people should use the die() function before the live... so that will clear any previews instructions and that function is only triggered once...
another thing could be that the instructions are called before the contents are retrieved from the ajax. therefore you should use .success to check if the ajax was successfully loaded and then trigger the click instructions.
as it seems that the <div id="storyItemComments_66" has not been picked up from the DOM.
Following from your comment to this answer
Can you try the following instead of show()?
$("#" + cmt2open).attr('display', 'block');
Can you place your javascript inside;
$(document).ready(function(){
//your code here
});
Not sure this will fix it but it's good practice I find.
Also have you alerted out your variables to see what you get?
What is the error you are getting if any?
Have you tried putting an alert at the top of the function to see if the click event works?
edit
let me know if the above does not fix it and I'll remove this answer to clear out the noise

Calling Javascript in a page after it's been loaded by jQuery GET

Imagine a normal page calling javscript in head. The trouble is some of the content isnt loaded untill i click on a link. Subsequently when this link loads the content it wont work. This is because i guess the javascript has already been run and therefor doesnt attach itself to those elements called later on. There is only standard html being called.
So for example this is the code which calls my external html.
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data).slideDown('slow');
});
});
If the html i was calling for example and H1 tag was already in the page the cufon would work. However because i am loading the content via the above method H1 tags will not be changed with my chosen font.This is only an example. The same will apply for any javascript.
I was wonering whether there is a way around this without calling the the javascript as well the html when its received from the above function
If you want to attach events to elements on the page that are dynamically created take a look at the "live" keyword.
$('H1').live("click", function() { alert('it works!'); });
Hope this is what you were looking for.
Does Cufon.refresh() do what you want?
As you said Cufon was just an example, I'd also suggest a more general:
$.get(url, options, function(html, status) {
var dom = $(html);
// call your function to manipulate the new elements and attach
// event handlers etc:
enhance(dom);
// insert DOM into page and animate:
dom.hide();
$target_element.append(dom); // <-- append/prepend/replace whatever.
dom.show(); // <-- replace with custom animation
});
You can attach event handlers to the data that you get via the get() inside of the callback function. For example
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data).find('a').click(function(e) {
// specify an event handler for <a> elements in returned data
}).end().slideDown('slow');
});
});
live() may also be an option for you, depending on what events you want to bind to (since live() uses event delegation, not all events are supported).
Andy try this. It will call the Cufon code after each AJAX request is complete and before the html is actually added to the page.
$.get('content.inc.php', {id:id}, function(data){
$('#feature').children().fadeTo('fast', 0).parent().slideUp('slow', function(){
$(this).html(data);
Cufon.replace('h1');
$(this).slideDown('slow');
});
});
JavaScript is not executed because of a security reason OR beccause jQuery is just setting this element's innerHTML to some text (which is not interpreted as a JavScript) if it's contained. So the security is the beside effect.
How to solve it?
try to find all SCRIPT tags in Your response and execute them as fallows:
var scripts = myelement.getElementsByTagName("SCRIPT");
var i = 0;
for (i = 0; i < scripts.length; i++)
eval(scripts[i].innerHTML);

Categories

Resources