JQuery: trigger () does not call associated target

I used trigger()

to check the radio button after all page content has loaded as the radio button value comes from a third party api.

I have set one parameter as default. So I used an event trigger()

to test the switch. The switch also has a click event.

In my code, only the radio button is selected, but the event doesn't fire. my code ...

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");
    });
});

      

+3


source to share


3 answers


You need to assign an event handler before firing the event.

When you actually fire an event, you still haven't hooked any listeners to that event. You do it on the next line. So the event is change

triggered, but nothing happens in 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

+5


source


You need to fire the event after attaching the 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 the long deprecated one $.fn.live

. And it's better to set a property checked

instead of an attribute.

+3


source


You need to hook up the change event before you actually fire the change event. I have included a script for the function you requested.

I changed the target of change-event to be the actual radio input since I didn't have your html, but usually you would most likely want to use the radio group name to bind the event as this is usually combined with one behavior - for example $("input[name='radioName']").change(function(){ // Change event code });

Sidenote: you can use '$' instead of 'jQuery' to run the 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");
});

      

+2


source







All Articles