jQuery - Check current state of radio button and hide div

后端 未结 1 1431
小蘑菇
小蘑菇 2021-01-18 21:28

QUESTION: How would I check the value of a radio button onload and if it is a certain value, perform an action based up on that? Referenced at the end of my

相关标签:
1条回答
  • 2021-01-18 22:12

    Well, I'm assuming that each radio button has a unique value, and they are all given the same name. In that case, what you want is the :checked selector:

    var $selected = $('input[name="RadioGroup"]:checked', '#someform');
    if($selected.length == 0) {
       // None is selected
    } else {
       var whichOne = $selected.val();
       // do stuff here
    }
    

    That will get you the value of the currently selected radio button. If you already have the id of the radio button you want to check, then it's as simple as:

    $('#someradiobutton').is(':checked') // returns true if checked, else false
    

    Specifically, since you specifically want to check on the slideshow value, I believe your if statement will become:

    if (jQuery('input[name="mainImageLinkHandleSelection"][value="display"]', '#section-of_homepage_display').is(':checked')) {
      jQuery('.main_link').hide();
    }
    

    EDIT: I see your issue now. The problem is that you hide all the .main_link elements, as well as the .homepage_display elements. But when you click on the homepage selection radio button, you don't then go through and re-display the .main_link element that is reflected by the yhlumberyardstraditional3[of_main_image_link_option] radio button group.

    Two things:

    1. Use the change event handler instead of click. This will prevent the whole animation sequence from needlessly running when an already selected radio button is clicked.
    2. When an element is shown, you'll need to see if any radio buttons are checked and then trigger the change event handler for those radio buttons.

    I've gone ahead an updated your fiddle with a proof-of-concept. The main change is as follows:

    var toShow = null;
    if (this.value === "slideshow") {
      toShow = '.homepage_display_slides';
    } else if (this.value === "static") {
      toShow = '.homepage_display_static';
    }
    
    if(toShow) {
        jQuery(toShow).show(duration);
        // If we just showed any checked radio buttons, let's re-trigger
        // them so they can update their groups and such
        jQuery('input:checked:visible', toShow).trigger('change');
    }
    

    I also took the liberty of generalizing the problem and shrunk the code down to 39 lines. Check it out here.

    0 讨论(0)
提交回复
热议问题