Dominique Deschatre
Dominique Deschatre

Reputation: 119

jQuery .show() and .hide() for cloned radio buttons

I have a series of radio buttons that were cloned. I wanted to do a simple thing as showing an especific div if the related radio is selected, and hiding if not. Here's the jQuery function:

$clone.find('[id^="mov"]').each(function(){
    $(this).click(function(){
            $clone.find('[id^="l"]').each(function(){
            if ($(this).is(":checked")){
                $clone.find('[id^="linear"]').each(function(){
                $(this).show();
                });
            } 
            });
            $clone.find('[id^="c"]').each(function(){
            if ($(this).is(":checked")){
                $clone.find('[id^="circular"]').each(function(){
                $(this).show();
                });
            } 
            });
            $clone.find('[id^="r"]').each(function(){
            if ($(this).is(":checked")){
                $clone.find('[id^="rotacional"]').each(function(){
                $(this).show();
                });
            } 
            });
            $clone.find('[id^="m"]').each(function(){
            if ($(this).is(":checked")){
                $clone.find('[id^="mudanca_config_mao"]').each(function(){
                $(this).show();
                });
            }
            }); 
    });
});

I managed to show the divs I want, but I can't seem to hide them. When I do the same thing for an else, it won't work and stops showing the div.

if ($(this).is(":checked")){
    $clone.find('[id^="linear"]').each(function(){
    $(this).show();
    });
}
else {
    $clone.find('[id^="linear"]').each(function(){
    $(this).hide();
    });
}

Also, I know this function is kind of repetitive and messy, so if anyone have a better and clean way of doing it, I'm open to suggestions. I'm new at jQuery and still learning :) Thank you very much!

Upvotes: 0

Views: 92

Answers (1)

James Brierley
James Brierley

Reputation: 4670

It's hard to see what the problem is without seeing your html. However, you're JavaScript can definitely be tidied up. The below should be equivalent to the JavaScript in your question.

$clone.find('[id^="mov"]').on('click', function(){
    $clone.find('[id^="linear"]').toggle(
        $clone.find('[id^="l"]').is(':checked'));
    $clone.find('[id^="circular"]').toggle(
        $clone.find('[id^="c"]').is(':checked'));
    $clone.find('[id^="rotacional"]').toggle(
        $clone.find('[id^="r"]').is(':checked'));
    $clone.find('[id^="mudanca_config_mao"]').toggle(
        $clone.find('[id^="m"]').is(':checked'));
});

Upvotes: 1

Related Questions