I have a checkbox with id myopt and I have a click event handler as below;
$("#globalBody").on("click", "#myopt", function (event) {
if ($(this).prop("checked")) {
// do something
} else {
// do something
}
});
Now in my code, I do
$("#myopt").attr("checked",true);
My question is this does not trigger the click event handler above. It gets called if I click the checkbox manually.
What is the issue ?
You need to use .trigger() to programmatically invoke the click handler
Execute all handlers and behaviors attached to the matched elements for the given event type.
Script
$("#myopt").prop("checked",true).trigger('click');
Note: I would recommend you to use change event
$("#globalBody").on("change", "#myopt", function (event) {
if (this.checked) {
// do something
} else {
// do something
}
});
//Change
$("#myopt").prop("checked",true).trigger('change');
Check this fiddle please https://jsfiddle.net/kwp7sjwf/2/
I have two versions depending on what you need. As I understand it, what you want is to click somewhere inside the #globalBody and check the state of myopt checkbox. In the above fiddle I did that, but I've placed in comments a code block that handles the 2nd version which is the case where you want to listen only when myopt checkbox state changes (clicks directly on the checkbox).
Hope it helps
Related
I'm using hammer.js and jquery.hammer.js in order to handle multiple different types of events (mostly tap events).
I made a wrapper function to be used for any/all tap event listener declarations.
This is the function.
var OnClick = function(button, CallbackFunction, TurnBackOnAfterStartCallback)
{
if(TurnBackOnAfterStartCallback != false)
{
TurnBackOnAfterStartCallback = true;
}
if(!button)
{
LogResult("Error: Attempted to create Hammer Click Event Listener without assigning a jQuery Object to listen too...");
return;
}
if(!CallbackFunction)
{
LogResult("Error: Attempted to create Hammer Click Event Listener without assigning a Callback Function...");
return;
}
$(button).hammer().on("tap", function(event)
{
var target = event.target;
// Disable the button so that we can't spam the event....
$(target).hammer().off("tap");
// We receive the event Object, incase we need it...
// Then we call our CallBackFunction...
if(CallbackFunction)
{
CallbackFunction(target);
}
// Renable the button for future use if need be.
if(TurnBackOnAfterStartCallback)
{
$(target).hammer().on("tap", CallbackFunction);
}
});
};
When I register an event using this function it works as expected. First it disables the event listener so you can't spam the event by clicking the button 100 times... Like so...
$(target).hammer().off("tap");
Then it preforms any callback functionality if there exists any...
if(CallbackFunction)
{
CallbackFunction(target);
}
Finally we re-enable the button for future use, unless we've specified that it will not be turned back on...
// Renable the button for future use if need be.
if(TurnBackOnAfterStartCallback)
{
$(target).hammer().on("tap", CallbackFunction);
}
This works perfectly during the first event launch... However, once I trigger the event again the Callback function is sent the event and not the event.target for some reason...
If I remove the .off and .on calls then it works as expected but can be spammed...
For a live example checkout this jsfiddle... It prints the result to the console... The first output is correct, everything after that isn't as expected.
https://jsfiddle.net/xupd7nL1/12/
Never mind, I had a dumb moment there...
The issue was that I was calling the event listener directly and not through my wrapper function, OnClick...
In other words change...
if(TurnBackOnAfterStartCallback)
{
$(target).hammer().on("tap", CallbackFunction);
}
to
if(TurnBackOnAfterStartCallback)
{
OnClick(target, CallbackFunction, TurnBackOnAfterStartCallback);
}
essentially I am wondering if it is possible to write a function so that if any item inside a specific container is clicked and nothing happens, it will alert that the feature has not been made available yet.
explanation:
what I mean by nothing happens is that the DOM or site does not change. So if a javascript or jquery function is called on click, it would not alert. if the item is a link to another site, it would not alert. but if nothing happens on the click event of an item inside a specified container, then it would alert.
The closest you could come would be to:
bind a click event handler to the container that would check if the event target was a link to another site and, if not, display the alert
make sure you stopPropagation() on all your event handlers.
Like this?
jsFiddle
$('a').on('click', function() {
if ($(this).attr('href') == '#') {
alert('the feature has not been made available yet.');
return false;
} else {
return true;
}
});
I have a button with a click event (from a 3. party library) which submits a form. I like to remove the click event, add my own function and call the original event after a validation.
I thought i just add an event.stopImmediatePropagation(); but that did not work. Maybe because of the order the events where added(?).
Is the another way to manage the event execution?
Or how can I get the old event to do something like this:
originalClickEvent = $('#button').doSomeMagicAndGetTheEvent('click');
$('#button').unbind();
$('#button').bind('click', function (event) {
if (valid()) originalClickEvent();
});
Look here Remove all JavaScript event listeners of an element and its children?
After you remove the event listeners you can attach your custom event.
If I've understood you correctly this is the effect you're searching for: http://jsfiddle.net/ftGHq/
In case the click event is just bound to one function you could overwrite that function:
var oldFunction = theOldFunction;
function myFunction(control) {
oldFunction(control);
}
$('#button').unbind();
$('#button').click(myFunction);
So I have a button inside a list row that is used to delete the row from the page (calls ajax stuff to delete the object represented by the row, but that's not important for my question). The whole row is bound to a click event which would redirect to another page.
In other words, the containing row is click bound and the inner button is click bound, which is causing me problems since clicking the inner button also triggers the containing row click event (as it should).
I've tried binding a hover event for all delete buttons that unbinds the row click on mouseover, and rebinds it on mouseout, like this pseudocode below:
$('.delete-button').hover(
function() {
$('.list-row').unbind();
$('.delete-button').bind('click', function() { /* delete action */ });
},
function() {
$('.delete-button').unbind();
$('.list-row').bind('click', function() { /* list row action */ });
}
);
This isn't working very well, and I'm convinced there is a better way to approach it. Should I take the button out of the containing list-row? It's way easier to have it in there since my list row contains custom attributes that have data I need for the ajax calls and I can just var rid = $('.delete-button).parent().attr('row-id'); to get the data, but I'm not opposed to change :)
Thanks!
In your click event handler for the button, you need to call e.stopPropagation(). This will prevent the event from bubbling up the DOM tree. More info here: http://api.jquery.com/event.stopPropagation/
edit: you already accepted (thanks!), but maybe this code snippet would help explain some of the concepts better:
$('.list-row').click(function() {
/* list row action */
});
$('.delete-button').click(function(e) {
// die, bubbles, die
e.stopPropagation();
// if you also need to prevent the default behavior for the button itself,
// uncomment the following line:
// e.preventDefault();
// note that if you are doing both e.stopPropagation() AND e.preventDefault()
// you should just `return false;` at the end of the handler (which is jQuery-
// sugar for doing both of these at once)
/* delete action */
})
There's a few ways of approaching this. As #jmar777 has already said you may attach an altered event to the click handler on the button, stopping propagation.
If you want to do this with the same function as you're applying to the div then you can approach it as such:
if($(event.target).is("input")) {
event.stopPropagation();
}
Another approach is to actually not bind the click event to the button, for any time the browser supports clicks on the containing element. As you will always trigger that, then you don't actually need the button to handle it too! This does require you to handle IE6 etc a little differently from everything else though...
Let your handler function return false
$('document').ready(function(){
$('[name=mycheckbox]').live('click', function(){
if($(this).is(':checked'))
{
alert('it is checked');
}
else
{
alert('it is not checked');
}
});
$('[name=mycheckbox]').click();
});
If the checkbox is checked and you click it, the alert box says, "it is not checked", but when the page runs and the click event is fired (with the checkbox checked), the alert box says, "it is checked". Why? Is the state of the checkbox not effected by the click event? Is it mousedown that changes the state?
Instead of click you should use the change event here, like this:
$('[name=mycheckbox]').live('change', function(){
And invoke it with the same trigger, like this:
$('[name=mycheckbox]').change();
The click is separate from the change, if you want the event to fire when the check actually has finished changing, then you want change, not click. Alternately, if you want to toggle it from it's initial state still, do this:
$('[name=mycheckbox]').click().change();
Instead of the live event (which I've found to be buggy at best) try binding a normal click even instead. I've done something similar which works fine with a .click event not .live("click",
I hope that helps :S
What is happening is quite subtle.
I have a button and checkbox linked to the following code:
$("#chkbx").click(function() {
if ($(this).is(':checked')) {
alert('checked');
}
else {
alert('unchecked');
}
});
$("#MyButton").click(function() {
$("#chkbx").click();
});
When I click on the checkbox, everything is displayed as you would expect.
When I click on the button, the reverse is true.
What is happening, is that when you click on the checkbox, it is firing the default click event before executing your code, and thus you code is taking the status from the aftermath of the default click event.
When you call the click method directly on the element, it is actually calling your click function and then executing the default event.
I'm not why this should be. or if this is intentional, or a bug.