jQuery Class selector not working - javascript

I'm struggling to make an alert come up when an anchor tag with a specific class is clicked inside of a div.
My html section in question looks like this...
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
The jQuery section is as follows..
$('.bar').click(function()
{
alert("CLICKED");
});
My problem is that I cannot get this alert to come up, I think that I'm properly selecting the class "next", but it won't pick it up for some reason. I've also tried almost everything on this page but nothing is working. If I don't try to specify the anchor tag i.e. $('#foo').click(function()... then it works, but there will be multiple anchor tags within this div, so simply having the alert executed when the div is clicked won't work for what I need. The website this is on is a search engine using ajax to send information to do_search.php. Within the do_search.php I make pagination decisions based on how many results are found, and if applicable, a next, previous, last, and first link may be made and echoed.
EDIT: I just figured it out, it was my placement of the .next function, since it wasn't created on the initial document load but instead after a result had been returned, I moved the .next function to the success part of the ajax function since that is where the buttons will be created if they need to be, now it works.

Try using the live() command:
$(".bar").live("click", function(){ alert(); });
Because you load your button via AJAX, the click event isn't binded to it. If you use the live() command, it will automatically bind events to all elements created after the page has loaded.
More details, here

.live is now deprecated and is the selected answer for this. The answer is in the comments in the selected answer above. Here is the solution that resolved it for me:
$(document).on('click','.bar', function() { alert(); });
Thanks to #Blazemonger for the fix.

You surely missed $(document).ready(). Your code should be:
$(document).ready(function(){
$('.bar').click(function()
{
alert("CLICKED");
});
});
Hope this helps. Cheers

Make sure you have included JQuery Library properly.
Make sure your script has written between $(document).ready() in short $(function(){ });
Demo : http://jsfiddle.net/W9PXG/1/
<div id="foo">
<a class='bar' href='#'>Next</a>
</div>
$(function(){
$('a.bar').click(function()
{
alert("CLICKED");
});
});

Related

jQuery onclick load randomly working with firefox

So I have a few "boxes" with an onclick function:
<div class="box" onclick="load(1);return false;"></div>
<div class="box" onclick="load(2);return false;"></div>
The onclick functions trigger a function that reads the content of a few seperate .php files (example1.php and example2.php).
These files contain other boxes made with fieldset instead of a div.
function load(num){
$("#loadthis").load("example"+num+".php");
}
And the function above is changing the content of this div down here:
<div id="loadthis">Load my fieldset boxes</div>
So far everything works, until I click on the fieldset boxes.
The background color of the fieldset should change when I click it and the radio inside the fieldset should be selected too (because of css styling), but both of this does not happen. But I can still select the radio when clicking the radio (not the box).
I have tested it in IE and in Chrome, this code works there most of the time.
But in firefox I cannot select the fieldset box 50% of the time.
I tried to experiment with the .on( class but it gives me the same effect.
$('fieldset.type-a').children('.row').children('.box.col-4').on("click", load);
function load(){
var index = $('fieldset.type-a').children('.row').children('.box.col-4').index( this );
index+=1;
$("#loadthis").load("fs"+index+".php");
}
Okay so after some searching I found that there is already an onclick function in a different .js file that being called:
function handleStep2() {
$('.step-form-2 input[type=radio]').change(function () {
$(this).closest('fieldset').find('.box').removeClass('active');
$(this).closest('.box').addClass('active');
$(this).attr('checked', 'checked');
});
$('.step-form-2 .select-box .box').click(function () {
$(this).find('input[type=radio]').trigger('change');
});
}
I am now going to try to merge the codes and see if that gets rid of the bug with the active class not being activated on click.
SOLVED: I solved it by indeed merging both the codes to 1 click function. Thanks for all your help guys, But I still wonder if this could be done a different way?
Look into event delegation, and if you're using jQuery it's easy
look into the jQuery API for .on(
Also you want to make sure you're using unobtrusive JS, so pull that out of your HTML, put it in a .js file as an event listener and load the script after the DOM has loaded as the last thing before your closing </body> tag
It should be a delay about loading php files content.
Is it work when you click one of them even takes time?
Maybe you should ajax for loading php files. By the way you can send data to php files using GET or POST methods.
You can check this examples.
If your function is initalized in an IIFE, inline js can´t access this function.
It´s weird that you say this sometimes works..
IIFE is a wrapper function to create capsules, so the client can´t modify your script in runtime.
Looks like this:
(function(){
/* code */
}());
It would be much better to create js-events:
on('body', 'click', '.box', function(e) {
console.log(e.target); // this is the clicked list item
});
Hope it helps..

JavaScript Event Handler jQuery

I am working on a hand me down project that was written by someone who was clearly better at HTML and JavaScript than myself. The html has AJAX links like this:
<ul class="subNav">
<li><a link="contacts.html">Contacts</a></li>
<li><a link="contacts_add.html">Add Contact</a></li>
</ul>
Which I think are handled in this code:
$('.subNav li a').click(function() {
var href = $(this).attr('link')
$('#mainStage').load(href, function() {
pageLoad();
})
})
All of the code above works perfectly.
My problem is I can't seem to recreate this functionality. I am using this HTML:
<div class="nameTitle colorOne"><a link="contacts_add.html">
<span class="firstNameField">Contact Name</span>
</a></div>
and this JavaScript:
$('.nameTitle').click(function() {
alert('')
$('#mainStage').load("contacts_add.html", function() {
pageLoad();
})
})
When I click the "nameTitle" class it should load contacts_add.html into the mainStage section of the page but I cannot see anything happen. I am sure someone fluent with this style of coding could tell me why my event never fires but the earlier code does.
Thanks in advance,
You should try altering your code to something like this:
$('.nameTitle').click(function() {
//This line finds the address to load
var address = $(this).children("a").attr("link");
//This line loads the address and then runs the pageLoad function when it has completed
$('#mainStage').load(address, function() {
pageLoad();
});
});
If this doesnt work it may be because the html is loaded dynamically. In this case you need to use .on, see this link here.
In response to Brett's comment below ive put together a jsfiddle showing .on in action here. Also i added .preventDefault as this could cause a problem.
try with
$('.nameTitle a').click(function() {
It can be that you're trying with a browser which accepts click only on 'a' tags, albeit they're getting rare hopefully.
The 'click' event will never be raised on your div, since there is an inner a element with an href defined. Once you click, the event will be raised on the anchor link first which will, by default, redirect to the location specified by the href. In order to get this working, catch the click when it is raised at the a:
$('.nameTitle a').click(function(e) {
e.preventDefault(); // prevent browser from following href
alert('');
$('#mainStage').load("contacts_add.html", function() {
pageLoad();
});
});
Demo -- Commented out the load, since that page isn't on this server. Also notice I changed your a element to have attribute href instead of link.

Why i can not trigger the jquery function?

This is a button to close the click but it fail and not work. I would like to know what is the tab ID since i did not think i assign one when i create a tab.
Thank you.
This is my attempt
js
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
html
<input type="button" id="closeTab" value="Cancel" class="submit"/>
I found my js code is working but the button can not trigger it? Why? thank you
latest try:
<script>
$(document).ready(function(){
$("#addlist").validate();
});
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
});
</script>
It still doesn't work so i think it is because the upper function ? How to fix this?
================================================================================
Also, are there any ways to clear my session in using this jquery function (what should i add for instance)?**Thanks
With javascript, you have to delay the execution of certain functions (like event handlers) until the page loads fully. Otherwise, it is attempting to bind a function to an element that doesn't yet exist. With jQuery, you can pass a function to jQuery to be executed on page load very easily like this:
$(function(){ /* code goes here */ });
So to use this with your code, you would do this:
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
});
});
This way, when the jQuery attempts to bind the function to #closeTab, it happens after the page has loaded (and after #closeTab exists).
Do you have any errors in the console?
Do you include jQuery before that click binding?
Try changing the window.parent.... to alert('clicked!'); and make sure you're actually getting there.
Also, make sure the click binding is inside of a:
$(document).ready(function(){
// here
});
A script can close only the windows it creates. It cannot close the tab which it didn't create.
To rephrase, cannot close tab only if unless but when created tab by script which is same that close window.
I hope this makes sense.
Maybe the form is submitted and the browser navigates to another URL before the code could run? Try replacing function() with function(e) and adding e.preventDefault(); to the beginning of the event handler.

Identical JQuery function is working for one link, not another

I have the function:
<script type="text/javascript">
$(function() {
$('#subbutton').click(function() {
$('#subbutton').hide();
});
});
</script>
It simply makes this button hide when clicked:
<a id="subbutton" class="button" href="javascript:TINY.box.show({url: 'follow',width:600,height:170,openjs:'initPopupLogin',opacity:30})"><span>Button</span></a>
Now, if i try to use the identical function, but with a link later on the page, it doesnt work (i have erased the original button at this point) Here is the code:
<div id="subbutton">
<span>Button</span>
</div>
I have tried putting the id in the anchor and in the span, nothing seems to be working for this link. Any idea why this isn't working? (I have deleted the original button so that this second button is a unique id on the page)
Try using .on instead to attach your event handler. I am suspecting the button is not in the dom at the time you attach the event handler.
$(document).on('click', '#subbutton', function() {
$(this).hide();
});
EDIT now that i understand the problem. You are better off giving the buttons a class and using a class selector.
.hide doesn't remove the element from the page so your selector will still be matching on the first element. You need to use .remove to remove the first element from the DOM so the second selector can work.
Also, little jQuery optimization. The nested call to $('#subbutton') is not needed. At best, it is harder to maintain, at worst, it could cause performance issues if you put this in a large loop. This is better.
$(function() {
$('#subbutton').click(function() {
$(this).remove();
});
});
You are missing a " after this:
<a id="subbutton" class="button
and Id has to be unique. Then it should work.
Don't reuse ids, they must be unique. pass the id to the function
Change your javascript to:
$(function() {
$('#subbutton').live("click",function() {
$(this).hide();
});
});​
http://jsfiddle.net/W2agx/
also don't reuse id's. use a class for multiple DOM elements that you want to be able to select together.

applying script to elements inserted via jquery .html()

i'm kinda new to scripting so this might be a bit basic, but i couldn't find an answer anywhere.
To improve my webpage loading time I made some HTML element load (via AJAX) and inserted only when a certain button is clicked, using the jquery .html() function.
That worked, but now all the jquery commands which referred to that element don't seem to apply. I'm guessing it's because the original commands were loaded before the new HTML?
For example, code like this:
$(document).ready(function(){
$('#myButton').click(function(){
$('#placeHolder').html('<div id="touchMe">click me</div>');
});
$('#touchMe').click(function(){
alert ("WORKED");
});
}
How do I make the #touchMe.click command apply to the new incoming HTML?
thanks a lot
Take a look at live()
$('#touchMe').live('click', function() {
Try -
$('#touchMe').live('click',function(){
alert ("WORKED");
});
Instead of
$('#touchMe').click(function(){
alert ("WORKED");
});
use
$('#touchMe').live('click', function(){
alert ("WORKED");
});
you use .live() or .delegate() function instead of click.
$(document).ready(function(){
$('#myButton').live('click', function(){
$('#placeHolder').html('<div id="touchMe">click me</div>');
});
$('#touchMe').live('click', function(){
alert ("WORKED");
});
}
note: the live on "mybutton" is not necessary in this example.

Categories

Resources