简体   繁体   中英

Checking radio button with jQuery doesn't trigger radio's onclick event

I have a pair of radios, to which I assign a function using bind(), on the pages.ready event. then, on the same ready event, I check for another input's value, and if it's value is "1" I preselect the second radio button when the page loads. here is a snippet.

<input type="radio" name="fpago" id="fpago1" value="1" />one
<input type="radio" name="fpago" id="fpago2" value="2" />two

...

$(document).ready(function() {
    $("#myspan").hide();

    $("#fpago1, #fpago2").bind('change click',function(){
        togglePlazo();
    });

//initial condition to preselect radio #2
    grupo = $("#id_grupo").val();
    if(grupo != '0'){
        $("#fpago2").attr('checked', true); //checks the radio, but doesn't trigger function
    }

});

...

--> see here for a more complete code

The problem is that, the radio does get checked if the condition is met, BUT the bound function togglePlazo() doesn't trigger...

If later I manually click the radio buttons, the function does get triggered, and the span toggles. It is only on the initial "check" made with jQuery, where the function does not trigger despite the radio getting changed.

I don't know what I'm missing, maybe I should bind more events other than change or click... I just can't find what I am doing wrong.

NOTE: I am using jQuery 1.4.2, but the fiddle is set to use 1.6.4 (it doesn't have 1.4.2 as an option)

Just trigger the click event when you set the checked attribute.

$("#fpago2").attr('checked', true).trigger('click');

Changing an attribute on the element doesn't fire a changed event... Neither by the native setAttribute or using jQuery's attr.

If you write console.log('yes'); inside imageTypeToggle function and you will see on page load in console yes will not print. you need to trigger like below

$(function () {
    $(window).load(function(){
    $("[name=image_type]").on("change",imageTypeToggle).trigger('click');
 })

$('input:radio[name="fpago"]').filter( [value="1"] ).prop('checked', true).trigger("change");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM