jquery trigger change event on checkbox - javascript

Is it possible to trigger change event on a checkbox using javascript/jquery?
Something like this (I run triggerChange on click of a button):
<label><input type="checkbox" id="chk"/>Label for chk</label>
<script>
function triggerChange(){
$("#chk").trigger("change");
}
</script>
When I run the above code I get this error: "trigger is not a function".

That trigger is not a function error message indicates something else is at play. According to this SO question:
What happens when a jQuery selector wasn't found?
no.good.at.coding says:
Do note however that you must ensure that selector is a jQuery object!
Otherwise, you could get an error indicating that "trigger is not a
function".
It's likely that you have forgotten jQuery?
As for your implementation, you should be fine the way you are using it. But trigger should be used to trigger event methods on elements that have already been attached via jQuery. Check out my demo:
Fiddle:
With click event: http://jsfiddle.net/fS4R5/1/
Without click event: http://jsfiddle.net/fS4R5/2/
HTML:
<label><input type="checkbox" id="chk"/>Label for chk</label>
JS:
function triggerChange(){
$("#chk").trigger("change");
}
$("#chk").change(function() {
alert("triggered!");
});
triggerChange();

In jQuery, you can usually trigger an event by calling it's eventhandler method withoud any function parameters.
For example a click handler can be assigned as such:
$('#mything').click(function(e){dostuff});
the click event in itself can be triggered by simply running:
$('#mything').click();
I suspect this can be done for every existing event in jQuery.

Be sure that Input of Type checkbox is enabled, in case is disabled trigger will not fire event
//fire event
$('#ceckBoxId').click();
$('#ceckBoxId').trigger('click');
or change checkbox checked val
$('#ceckBoxId').prop('checked', true);
$('#ceckBoxId').prop('checked', false);

I think the preferred method since 1.9.1 is 'on'. Specially if you use dynamically added checkboxes.
Say you have a div with id='divCOntent' and on it is a checkbox with id='cballaut', you could do this
$('#divcontent').on('click', '#cballaut', function (e) {
alert(this.checked);
});

use prop method.
$('#myCheck').prop('checked', true);
$('#myCheck').prop('checked', false);

Related

JQuery: trigger() not calling related target

I have used the trigger() for checking the radio button after loading all the page content as the radio button value is coming from third party api.
I have make one option checked by default. So I used trigger() event for checking the radio button. The radio button have also it's click event.
In my code only radio button get selected but event is not firing.
my code is...
jQuery(document).ready(function($) {
jQuery("#btn_03").attr('checked', 'checked');
jQuery("#btn_03").trigger("change");
jQuery(".class input[type='radio']").live("change", function($) {
alert("clicked");
});
});
You need to assign the event handler before you trigger the event.
When you are actually triggering the event, you still haven't attached any listeners for that event. You are doing that in the next line. Thus the event change does get triggered but nothing happens on that event.
You can do it this way
jQuery(document).ready(function($) {
jQuery("#btn_03").attr('checked', 'checked');
jQuery(".class input[type='radio']").on("change", function($) {
alert("clicked");
});
jQuery("#btn_03").trigger("change");
});
Also use "on" to bind events instead of "live" as per the latest jQuery documentation
You need to trigger event after you attach event handler:
jQuery(".class input[type='radio']").on("change", function(e) {
alert("clicked");
});
jQuery("#btn_03").prop('checked', true).trigger("change");
Also use $.fn.on instead of long time ago deprecated $.fn.live. And it's better to set checked property instead of attribute.
You need to hook the change event before you actually call the change event. I've included a fiddle of the functionality you requested.
I've changed the change-event target to be the actual radio input since I did not have your html, but normally you would most likely want to use the name of the radio group to hook the event to, since those are usually coupled with a single behaviour - like so $("input[name='radioName']").change(function(){ // Change event code });
Sidenote: You can use '$' instead of of 'jQuery' to start an expression.
http://jsfiddle.net/du58fo3t/
$(document).ready(function() {
$("#btn_03").attr('checked', true); // Check radio button
// Hook change event on radio button
$("#btn_03").change(function() {
alert("clicked");
});
// Trigger change on radio button
$("#btn_03").trigger("change");
});

Trigger "change" event on input does not work

I created kind of custom checkbox's plugin for my own project.
So I wanted to trigger <input type="checkbox"> manually clicking on another button like this:
$("a#triggerButton").click(function(){
$("input[type='checkbox']")
.prop("checked", true)
.triggerHandler("change");
});
Here is a typical example of what I'm doing: http://jsfiddle.net/fstqvq8k/3/
It seems that the event isn't triggered. I used a lot of methods but not seems to work too:
$("input[type='checkbox']").change();
$(document).on("change", "input[type='checkbox']", function(){});
Since you dynamically create your button:
$("#container").on("click", "#triggerButton", function() {
$("#customCheckbox")
.prop("checked", true)
.trigger("change");
});
http://jsfiddle.net/fstqvq8k/4/
Also from the Docs read:
The .triggerHandler() method does not cause the default behavior of an event to occur (such as a form submission).
You can also trigger the checkbox event like..
$("input[type='checkbox']").click();

jQuery Simulate onClick

I am trying to simulate an onclick event on a drop down.
I have an IE object that is going to a page and I need to change a dropdown which has an onchange event:
$('select[name="blah"]').val(3).trigger('change');
$('select[name="blah"]').change(function(){
alert('changed');
});
When I try this, I would expect the alert to fire as it's technically an onchange.
http://jsfiddle.net/3y5hmyf0/
Is there a way to acomplish this?
More Details
My tool is controlling another IE page through an object. It navigates to the page and finds the select drop down on the page. From there, if you did it manually it has an onchange event when making a selection.
I am trying to get jQuery to simulate as if it was being clicked by a person to it triggers that on change event.
I have tried .trigger and .change and couldnt get either of them to work.
The only reason your code does not work is the order you are executing it. You need to connect the handler before triggering it:
JSFiddle: http://jsfiddle.net/3y5hmyf0/1/
// Wire up event handler
$('select[name="blah"]').change(function(){
alert('changed');
});
// Now generate the event
$('select[name="blah"]').val(3).trigger('change');
Note: Your manual change trigger is still required as a change event must normally be triggered by user interaction. Setting the value is not enough.
$('select[name="blah"]').change(function(){
NotifyChanged();
});
function NotifyChanged() {
alert('changed');
}
If you want to test the logic in the changed function, just call it.

I can't prevent a button click event on JQuery

I have a button that clears a list, the click on this button shows a dialog that asks for validation (Yes/No). What I want is to disable the "Clear" button after clearing the list (Click on Yes). Here's my code :
$('#clearBtn').click(function() {
$('#alert5').show();
$('#bg').show();
$('#Yes').click(function(){
$('.list1').empty();
$('#clearBtn').disable(true);
$('#clearBtn').click(function(e){
e.preventDefault();
});
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
});
the preventDefault() function doesn't seem to work.
First never nest event handlers.
$('#cleatBtn').click(function () {
$('#alert5').show();
$('#bg').show();
});
$('#Yes').click(function () {
$('.list1').empty();
$('#cleatBtn').attr('disabled', true);
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
If you just want to disable then use the following syntax
$('#cleatBtn').attr('disabled', true);
Remove the innermost event completely.. That is not required.
Use on to bind the events, if you want the button to be enabled but turn off the event handler using off
One more option you have is to apply a class to the button when you press yes and execute the code only when the class is not present.
$('#cleatBtn').click(function () {
if( !$(this).hasClass('active')) {
$('#alert5').show();
$('#bg').show();
}
});
$('#Yes').click(function () {
$('.list1').empty();
$('#cleatBtn').attr('disabled', true);
$('#cleatBtn').addClass('active');
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
To disable a button, call the prop function with the argument true on it:
$('#cleatBtn').prop("disabled", true);
e.preventDefault(); is the correct way of cancelling events. Some older browsers also expect a return type of false. Which I think will cause jQuery to call preventDefault()?
Here's a good answer: What's the effect of adding 'return false' to a click event listener?
I think your structure looks a bit odd. you don't need to attach click events within a click event.
Just attach them all separately on document.ready events. At the moment they are nested, then go back to trying to cancel your event. The dom tree might be confused by the way the events are nested.
Hope that helps.

trigger Jquery function after an auto focus

is it possible to trigger a function after an autofocus? I tried but when my textarea get the autofocus i need to click away then to click again on my textarea to trigger the function
my code is :
$('#test').focus();
$('#test').focus(function() {
alert('ok');
});
Try swapping the code around. You're event wasn't attached to the test element the first time you call focus()
$('#test').focus(function() {
alert('ok');
});
$('#test').focus();
This is because you are setting the trigger after you set the focus.
Rearrange your code and this will work fine.
The .focus() method has two different meanings based on the parameters it is passed.
In your first statement.
$('#test').focus();
This is setting the focus to the element with ID test.
Your second statement though
$('#test').focus(function() {
alert('ok');
});
What is happening here is jQuery is attaching an event handler to the focus event of the element. I suggest adding your event handlers when the DOM is loaded, then calling the .focus() event when required (which will trigger the alert).
$(function(){
$('#test').focus(function() {
alert('ok');
});
});

Categories

Resources