Trigger click on radio button as part of document ready

I have a dynamic radio button list as part of my application and, upon the user making a selection, I reveal additional content using a jQuery click function. This all works fine unless the dynamic list of radio buttons only has one option. With only one option, the radio button itself is selected by default, but the click event doesn't fire unless the user clicks the radio button.

Is there a way to trigger the click event at document ready so that, if there is only one option, the user doesn't have to make a redundant click?

This is the jQuery code I'm using which, again, works fine as long as the user makes a selection.

Thank you!

    jQuery('input[name="location"]').click(function(){
        var data = {location : jQuery(this).val()};
        jQuery.ajax({
            url: "/custom.php",
            type:'POST',
            data: data,
            dataType: 'html',
            success: function(result){
                jQuery('#div-custom').html(result).show();   
            }
        }); 

Answers


You can check how many radio buttons your selector matched by checking the length property. If it's one you can then trigger the click on that button manually, like this:

jQuery(function($) {
    var $locations = $('input[name="location"]').click(function(){
        $.ajax({
            url: "/custom.php",
            type:'POST',
            data: { location : $(this).val() },
            dataType: 'html',
            success: function(result) {
                $('#div-custom').html(result).show();   
            }
        }); 
    });

    if ($locations.length == 1)
        $locations.click();
});

Note also that the first parameter of the document.ready handler is a reference to jQuery, so you can alias that variable as the normal $ to avoid having to use the verbose jQuery everywhere.


Need Your Help

Link framework against App and Test Target

ios objective-c xcode objective-c-runtime sentestingkit

I have a custom Framework I use within my normal App target as well as the corresponding UnitTest target. Turns out that confuses the runtime in such way that it is unable to choose the correct

Use of PHP in CSS vs Adaption via JS[General]

javascript php html css wordpress

I have a general question about the use of PHP in CSS.