jQuery click event not firing on button element - javascript

I've got a simple If statement that checks if a checkbox is check or not that is called on a click event, however the click event appears to not be working.
I've for two dummy alerts into the if just to see if it being hit or not but neither of them are.
HTML:
<input id="cookie-checkbox" name="cookie-checkbox" class="cookie-checkbox" type="checkbox" checked><label for="cookie-checkbox">I give consent for the use of cookies on this website.</label><br /><br />
<button id="cookiesbutton" type="button" class="btn btn-default">Send</button>
JS:
(function () {
$('#cookiesbutton').click(cookiesDismiss());
});
function cookiesDismiss() {
var cookieConsent = $('#cookie-checkbox');
if (!cookieConsent.checked) {
alert("Cookie removed");
}
else
{
alert("Modal hidden");
}
}
I have a fiddle set up with the code at: JSFiddle
I'm almost sure that I'm missing something really, really small and simple, but I just can't seem to see it.

You need to give the click handler the reference to your cookiesDismiss() function, not the result of the function.
Also note that you need to precede the document ready handler with a $, and checked is not a property of a jQuery object; you need to use prop('checked') to get the state of the checkbox.
$(function() {
$('#cookiesbutton').click(cookiesDismiss); // note the removal of ()
});
function cookiesDismiss() {
var cookieConsent = $('#cookie-checkbox');
if (!cookieConsent.prop('checked')) {
alert("Cookie removed");
} else {
alert("Modal hidden");
}
}
Updated fiddle

OK, you clearly need to first get your JavaScript fundamentals straight :) But, here are your mistakes:
On the first block of code, you seem to write an Immediately Invoked Function Expression (IIFE). In JavaScript, the following is a function declaration:
function myFunction() {
// My awesome stuff
}
Without anyone else invoking this function, it is pretty much useless. You can invoke the function as myFunction() or invoke the function immediately as it is declared as:
(function myFunction() {
// My awesome stuff
})();
This pattern is mostly used to prevent your function body from exposing variable on global scope.
so, in your case, the click event handler was never registered because the function was never invoked.
Now, you know what a function invocation is. myFunction() invokes the function. While myFunction gets a reference to a function.
When registering event handlers, the argument you pass is a reference to a function.
$('#myButton').click(myFunction);
So, you say, invoke my function myFunction everytime $('#myButton') is clicked. So, your mistake was you invoked the function cookiesDismiss() immediately, so what was registered as a handler for the button click was whatever was returned by your function cookiesDismiss which is nothing (undefined) and therefore nothing happens.
Others have placed the correct code here, but you should definitely invest time learning the fundamentals.

Whenever you add parentheses "()" to a function its get executed/evaluated at that time only and in your case it assigned the evaluated value of the function instead of actual function.
Eample:
Where "target" is the ID of the html control.
$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});
or
$( "#target" ).click(showAlert);
function showAlert(){
alert( "Handler for .click() called." );
}
In your case:
As funation name is "cookiesDismiss" it should be as below mentioned code:
$('#cookiesbutton').click(cookiesDismiss())
(function () {
$('#cookiesbutton').click(cookiesDismiss);
});
Hope this will help you :)

1st: You missed the $ sign
2nd: $('#cookiesbutton').click(cookiesDismiss()); fire the event in the beginning.
3rd: .checked is wrong. You can use .is(":checked")
4th: Rory McCrossan provided the solution.

Related

JQuery click() event listener not working

im trying to get a lil project going but im stuck on a very annoying thing.
$(document).ready(function() {
$("#search-button").click(console.log('hello'))
});
as you can see im targeting a search button with the id search-button and as soon as i click it something should happen. in this case i put a console.log in to test if it works but it doesn't. it always logs it as soon as i load the page , not when i click the button i target. ... what am i doing wrong
if you need more info on this pls tell me i tried to keep it as simple as i could
ty for your help
O.k
The click handler needs a function argument, not just the console.log by itself. Try this:
$(document).ready(function() {
$("#search-button").click(function() {
console.log('hello');
});
});
Inside of .click should be a handler .click(handler) and the handler should be a function. The browser is reading the code and when it hits console.log('hello'), it does it! It's seeing .click etc, but it doesn't matter; it next sees console.log and does it.
Try
$(document).ready(function() {
$("#search-button").click(function() {
console.log('hello');
});
});
As others have mentioned, the click function requires its own callback function. You can also use this, without requiring the use of document:
$("#search-button").on('click', function() {
console.log('hello')
})
I hope You're using jQuery version 3 or up. if you use 3 or up jquery version the good practice is you use Document binding Example:
jQuery(document).on('click', '#search-button', function(event) {
//your Code here...
console.log('hello');
});

Pass function to click event jQuery

I am just wondering what I need to do to pass the clickAssistanceToggle function to my jQuery click event, I have taken a look at some of the answers on here and can't find a simple solution to this.
So far I have this code:
function clickAssistanceToggle() {
$('.car-hub-header-help, #assistance-overlay, .assistance-close-btn').click(function(){
$('#new-car-hub, #new-car-offer').toggleClass('assistance-active');
$('#pulman-assistance').toggleClass('pulman-assistance-active').css("top", fixedPositionCalculator);
$('#assistance-overlay').toggleClass('assistance-overlay-active');
$('#new-car').toggleClass('assistance-active-body');
$('#new-car-offer-cta').toggleClass('assistance-active-cta');
});
};
$('.new-car-general-enquiry-btn').click(function(){
clickAssistanceToggle();
});
As you can see the function wont run like this because it hasn't been passed as a parameter, I have tried passing the function like so:
$('.new-car-general-enquiry-btn').click(function(clickAssistanceToggle){
clickAssistanceToggle();
});
However this does not seem to work, any idea how I can pass that function to the click event? Thanks
You can call like this,
$('.new-car-general-enquiry-btn').click(clickAssistanceToggle);
Or
$('.new-car-general-enquiry-btn').click(function(){
clickAssistanceToggle();
});
Also there is a chance that, .new-car-general-enquiry-btn element is not being rendered at the time of binding the event. If so you need to wrap the code inside dom ready event.
$(document).ready(function() {
$('.new-car-general-enquiry-btn').click(function() {
clickAssistanceToggle();
});
});
Instead of
$('.new-car-general-enquiry-btn').click(function(clickAssistanceToggle){
clickAssistanceToggle();
});
You need to use
$('.new-car-general-enquiry-btn').click(clickAssistanceToggle);
Basically you need to pass the function to be executed when a click is performed on a .new-car-general-enquiry-btn element.

appending a new function at the end of list of functions assigned to a javascript event

Let's say, I've a input button like this:
<code>
<input type="submit" value="Submit" onclick="fxn1();fxn2();fxn3();"/>
</code>
Now, i wan't to add a new function fxn() (prepend or append) to the list of functions already assigned to onclick event. How would I do that? Also, the number of functions assigned to onclick is not known and hence can be anything greater than 0 or even 0 sometimes.
If you don't care whether it's prepended or appended or even inserted in the middle, and since you're already using jQuery (based on the tag you assigned the question), then use .click() to add the new function as a listener for the click event.
Here's a fiddle demonstrating: http://jsfiddle.net/trott/b67zN/2/
Or if you just want to see the code here, demo HTML looks like this:
<input id="clickme" type="submit" value="Submit" onclick="alert('foo');"/>
And demo JS looks like this:
function secondListener() {
alert('bar');
}
$('#clickme').click(secondListener);
jQuery.Callbacks do the needful. introduces in jQuery v1.7
The following are two sample methods named fn1 and fn2:
function fn1( value ){
console.log( value );
}
function fn2( value ){
fn1("fn2 says:" + value);
return false;
}
// Supported Flags :
// once: Ensures the callback list can only be fired once (like a Deferred).
var callbacks = $.Callbacks( "once" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );
Reference
You need to enter your functions as a part of already assigned function. What I mean is instead of appending new function on some condition call those functions from your one and only onclick function based on the condition.
Its just as simple as $('input').click(fxn);
And you may need to remove any handler from that element in future.
You could use unbind for that. But it will remove all the click handlers that have been attached to the element.
To avoid it and to remove just one event handler, you can do bind with namespace.
$('input').bind('click.fxn', fxn);
'click.fxn', can be explained as event name(click) followed by a . and some string(fxn) to distinguish the specific event handler.
So, if you want to remove fxn function you could do $('input').unbind('click.fxn').
It will only remove the fxn handler.
I hope this helps.

Not work my function after click?

I not know why not work following code for my function(alert()) and is run my function(alert()) after tow times click on button, did you can guide me?
Demo:(Here see my full code) http://jsfiddle.net/pRXQ7/1/
$('.iu').click(function() {
if(alert() == true){
alert('ok')
}else{
alert('no')
}
});
By naming your function alert, you've effectively overridden the native javascript alert function. Name it something else.
Also, in your alert function, you are referencing this. In the scope of the function, this points to the document object, not the element which was clicked. Try passing the element instance to your function from the click event handler.
See http://jsfiddle.net/pRXQ7/15/

jquery function not getting called inside of an ajax function

So im trying do disable links on some <li> ellements that have been loaded in from another page using an .load() function, but for some reason i'm not able to effect those list items.
var from_post = false;
$(document).ready(function() {
//so this is the function that loads in data from another page
$("#gallery").load('http://localhost/index.php/site/gallerys_avalible/ #gallerys_avalible'), function() {
console.log('hello');
// sense there are no other li elliments on the page i thought this
// would be okay. but this function never gets called, i've moved it
// all over i just recently attached it to the load function thinking
// that maybe if the load was not complete it would not run, but i
// have had no luck.
$('li').click(function (e) {
e.preventDefault();
console.log("I have been clicked!");
return false;
});
};
$('#addNew').click(function () {
console.log('i got called');
$('#new_form').fadeIn(1000);
});
$('form').submit(function() {
if(from_post) {
//submit form
return true;
} else {
//dont submit form.
return false;
}
});
any help would be greatly appreciated, oh and the other thing is that i can run this function through firebug, and it works 100% fine. so im stumped.
You are closing your call to .load() too early. You have:
$("#gallery").load('http://...'), function() {
That just calls load and then declares a function. But, that function is not bound to the success handler and it will never be executed. You need the ) to be on the other side of the function declaration so that the function is included as a parameter to your call to load:
$("#gallery").load('http://...', function() {
...
});
Fix that and your code works: http://jsfiddle.net/gilly3/WdqDY/
Try a future-proof event observer like live or delegate:
$('li').live('click', function(){})
or, this method is preferred if you know the parent:
$('#gallery').delegate('li','click',function(){})
The reason for needing this is your click events are being bound to elements that are on the page at the time of the binding. Any li's added later will not see that binding which is how live or delegate works. They bind to the parent and traverse the child nodes every (click in this case) event to see if the event applies to an existing child.
Use .live('click', ...) or .delegate() instead of .click(...).

Categories

Resources