jQuery Script in External .js file not firing - javascript

I have a small piece of script in an external .js file that will not run. Here is the script:
$(document).ready(function () {
$('#chkAllTracts').change(function () {
alert("fired");
})
});
I have a number of other functions in the same .js file that use some jQuery and they all work fine but this is the first jQuery I have attempted to use inside this syntax:
$(document).ready(function (){ }
All I am trying to do is make an alert open when a checkbox is changed (checked or unchecked). The checkbox element "chkAllTracts" is added dynamically using jQuery before this function is called.

$('#checkbox1').mousedown(function() {
if (!$(this).is(':checked')) {
alert("test")
}
});
something like that? (edited)

This worked for me:
$(document).ready(function(){
$("body").append(
$("<input>")
.attr("type", "checkbox")
.change(function(){ alert("It works!"); }))
});
When the document is ready it includes in the body the checkbox input with the change event set to fire the alert message.

It is because your element is dynamically added to the DOM. jQuery selectors would not get hold of it when jQuery first initialise. What you need to do is
$('body').find('#chkAllTracts').change(function () {
alert("fired");
});
I think that should solve your problem.

Related

jQuery bind event not firing on elements loaded via $().load()

I have a DIV that is in an .html file that is loaded into my document via:
$(document).Ready( function() {
$("#contentDiv").load("some.html")
//some.html contains a button id=saveButton
$("#saveButton").click( function () {
alert("Here I am!");
}
});
The event will not fire. If I cut the content of some.html and put it in the document, uhm, "physically", the event will fire.
So, I am pretty sure this issue is related to the fact that the html is injected via .load().
It's bothersome, because if you look at the page source, all the HTML is in fact there, including the button.
So, the question is, is there ANY way to make this work? I am using .load() to reduce page complexity and increase readability, and, code-folding notwithstanding, I really do not want to have to pull all this HTML into the document.
EDIT: This code was just typed in off the cuff. It's not a cut-n-past of the actual code, and it is just to demonstrate what the problem is. But, thanks for pointing it out.
EDIT2: Grrrrrrr. });
load() is asynchronus so you need to the job in the callback :
$(document).ready(function() {
$("#contentDiv").load("some.html", function(){
//some.html contains a button id=saveButton
$("#saveButton").click( function () {
alert("Here I am!");
});
});
});
Hope it helps :)
one way is by adding to the some.html the script line which will be loaded as the div appears.
You can add this script to some.html(in a script tag):
registerButton();
and then you can define registerButton() in your current document.
other way, if I remember correctly is by using something like the function bind( )
If you want to fire event on element which was not available at the time when DOM was ready then you need to use .on event.
http://api.jquery.com/on/
$("#saveButton").on("click", function() {
alert("Here I am!");
});
jquery load() function is asynchronous. If you want to bind events to the loaded content, you should put the code into the callback function:
$(document).ready(function() {
$("#contentDiv").load("some.html", function() {
//you should put here your event handler
});
});
Your issue is that jquery load() function is asynchronous as #lucas mention. But his code has syntax errors, try this:
$(document).ready(function () {
$("#contentDiv").load("some.html", function () {
$("#saveButton").click(function () {
alert("Here I am!");
});
});
});
Hope it helps now
You need to bind the event handler either after the load OR to the container of the HTML from the load
$(document).ready(function() {
$("#contentDiv").load("some.html", function() {
$("#saveButton").on('click',function() {
alert("Here I am! Bound in callback");
});
});
});
OR use: (not needed that it be in the document ready just that the contentDiv be present)
$("#contentDiv").on('click','#saveButton',function(){
alert("Here I am! bound to container div");
});
EDIT: load on the SAVE button click (per comments) (this makes no sense though)
$(document).ready(function() {
$("#saveButton").on('click',function() {
$("#contentDiv").load("some.html", function() {
alert("Here I am! Bound in callback");
});
});
});

jQuery not working after loading additional content

I am quite new to javascript, but I am using it at my website. Last week I found a script that loads additional content to my page via jQuery. Everything was all right until I noticed that my other scripts stopped working because of that. For example I have a script that binds checkboxes:
<script>
$(document).ready(
function() {
$('.class_of_checkbox').click(
function() {
if(this.checked == true) {
$(".class_of other_checkbox").attr('checked', this.checked);
}
}
);
}
);
</script>
It is inline code. I have read that it could be caused by function ready(), which fires only when the DOM is loaded, but I am not sure how to solve this problem.
Dynamic elements loaded with ajax needs delegated event handlers :
$(document).ready(function() {
$(document).on('change', '.class_of_checkbox', function() {
if (this.checked)
$(".class_of other_checkbox").prop('checked', this.checked);
});
});
Replace the second document with the closest non-dynamic parent, use prop() for properties, and use the change event to capture changes in the state of a checkbox.
Use $.ajaxComplete to rebind your actions when the ajax call completes
http://api.jquery.com/ajaxComplete/
$(document).ajaxComplete(function() {
$('.class_of_checkbox').click(
function() {
if(this.checked == true) {
$(".class_of other_checkbox").attr('checked', this.checked);
}
}
);
});

A click function not working

my a click jquery function is not working, it just doesn't give any errors at console at all too.
Here is the link -
Edit
and here is the click function
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
It doesn't popout the alert box, nor it does show me error in console.
Okay, someone asked for more info -
The link is added with jquery, by pressing button, and as id it takes one of the input fields value and inserts it as link with id from input field. There are no duplicate ids, all javascript scripts are located at the end of head tag, and the a click function is located last in part.
Based on your edit that the <a> tag is being inserted dynamically, you'll need to use jQuery's .on() (jQuery version 1.7 and later) or .live() method to attach the click handler.
This code should work, so I suppose there is some other error before this code runs that prevents correct Javascript execution.
Edit: OR the DOM is not yet ready when you insert the Javascript code. Then you should use
$(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});​
});
Are you wrapping it on the ready event or after the element has been displayed? If so then it should work;
http://jsfiddle.net/sWeRf/
Either place this code after the Edit on the page, or put it in the head with $(document).ready(function() { //Place code here. });
Can you try replacing your JS code with the following (put between the HEAD tags)
<script type="text/javascript">
$(document).ready(function(){
$('a#lang').click(function(){
alert($(this).attr('id'));
});
});
</script>
Are you checking the document is loaded before applying your JQuery click handler?
e.g.
$(document).ready(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
});
Instead of using document.ready you can use an anonymous function that does the same thing.
Like this:
$(function() {
$('a').click(function() {
var item = $(this).attr("id");
alert(item);
return false;
});
});
To remove the item do this:
$('#language_c').remove();

jquery that just waits

I normally set up my javascript code to have a function. But due to the fact that the application generates most of the HTML and javascript calls from a VB6 application I would like to create a jQuery function that is more like a listener. So for example if I have a td tag that has the class 'gridheader1' I would like the jQuery to wait for it to be clicked.
I'm assuming that I would use the bind... But I'm getting javascript errors with it... If you can offer suggestions on where my code is wrong that would be great.
$('.gridheader1').bind('click', function()
{
alert('hi I got clicked');
});
Again this just has to sit out there on the main .js file. It isn't attached to any functions. Please let me know.
Thanks
you want
$('.gridheader1').bind('click', function(){
alert('hi I got clicked');
});
note the dot at the start of selector - it means class
// static tags
$(function(){ // DOM ready
$('.gridheader1').click(function()
{
alert('gridheader1 clicked');
});
});
// or if the tag is loaded via ajax use 'live'...
$(function(){ // DOM Ready
$('.gridheader1').live('click', function()
{
alert('gridheader1 clicked');
});
});
// or if you already have a function defined that you want to call, you can pass in the function instead of using an anonymous function.
function alertAboutStuff(){
alert('gridheader1 clicked');
}
$(function(){
$('.gridheader1').click(alertAboutStuff);
// $('.gridheader1').live('click', alertAboutStuff); // for tags loaded via ajax
});

Trigger a jQuery Event Handler Assigned in a Different Code Block

I have a case where a click handler is defined/assigned in one jQuery code block (file) and I want to trigger it from another click event defined/assigned in a different jQuery code block. How can I accomplish this?
The following code is a greatly simplified version of what I am trying to accomplish. The behavior I want to see is a JavaScript alert "Element One" when I click #Element2.
Example HTML:
<p id="Element1">Element One</p>
<p id="Element2">Element Two</p>
First jQuery code block:
$(document).ready(function() {
$('#Element1').click(function() {
alert('Element One');
});
});
Second jQuery code block:
$(document).ready(function() {
$('#Element2').click(function() {
$('#Element1').click();
});
});
UPDATE: My original example actually works. I was building upon my field hint jQuery UI Dialog solution, and didn't account for about the 'clickoutside' handler that I was using. Adding a check to for the second element in my 'clickoutside' handler allows the dialog to display.
You need to trigger a click when you click on the first element. You can use the trigger method for this.
function element1Hanlder () {
alert('Element One');
}
$(document).ready(function() {
$('#Element1').click(function() {
alert('Element One');
});
});
$(document).ready(function() {
$('#Element2').click(function() {
$('#Element1').trigger('click');
});
});
EDIT: This is based on JohnP's "trigger" suggestion (so you should choose him as the right answer)...
If I load this block from an external js file...
$(document).ready(function() {
$('#Element1').click(function () {
alert( $(this).text() );
});
});
Then load this in a script tag within the HTML itself...
$(document).ready(function() {
$('#Element2').click(function () {
$('#Element1').trigger('click');
});
});
Seems to be working as intended.

Categories