keewee279
keewee279

Reputation: 1654

jQuery: show / hide Div when first or second radio button is selected

I am new to jQuery and hope someone here can help me with this.

I am trying to show / hide a div ('requestDetails') if the first OR second of a variable range of radio buttons is selected (the reason for this is that I would like to avoid hard-coding specific values to check for).

So far I only have a hard-coded solution but this doesn't work properly and I am not sure about how to address only the first and second radio button without this.

I tried to avoid using IDs or further classes on the radio buttons to reduce code but can add this if recommended.

My jQuery:

$('[name=requestType]').on('change', function(){
    if( ($('[name=requestType]').val() == 'value1') || ($('[name=requestType]').val() == 'value2') ){
        $('#requestDetails').show();
    }else{
        $('#requestDetails').hide();
    }
});

My HTML:

<input type="radio" name="requestType" value="value1" />Value1  
<input type="radio" name="requestType" value="value2" />Value2  
<input type="radio" name="requestType" value="value3" />Value3  
// ...
<div id="requestDetails" class="hidden"> ... </div>

Many thanks in advance for any help, Mike

Upvotes: 0

Views: 970

Answers (3)

loli
loli

Reputation: 1068

With no hardcoding, use the parent containing the inputs and use :nth-child selector. See jsfiddle for example :

$('[name=requestType]').on('change', function () {
    if($('#parent input:nth-child(2)').val() == $(this).val() ||$('#parent input:nth-child(3)').val() == $(this).val())
    $('#requestDetails').toggle();
});

http://jsfiddle.net/cwahL1tz/11/

Also made one with the exact behavior you wan to obtain : http://jsfiddle.net/cwahL1tz/13/

Upvotes: 0

david tallon
david tallon

Reputation: 424

If I were you, I would identify the buttons you would like to use as triggers for this show/hide event with a new class. Then attach the event to this class of button. This does not add much in code overhead.

Example:

<input type="radio" class="special" name="requestType" value="value1" />Value1  
<input type="radio" class="special" name="requestType" value="value2" />Value2  
<input type="radio" name="requestType" value="value3" />Value3  


$('.special').on('change', function(){
    if( ($('[name=requestType]').val() == 'value1') || ($('[name=requestType]').val() == 'value2') ){
        $('#requestDetails').show();
    }else{
        $('#requestDetails').hide();
    }
});

This will result in button 1 and button 2 affecting the div with id=requestDetails, while button 3 or any others without the class will not.

Upvotes: 1

Balachandran
Balachandran

Reputation: 9637

try

$('[name=requestType]').on('change', function () {

    $('#requestDetails').toggle((this.value == 'value1' || this.value == 'value2'));

});

DEMO

Upvotes: 3

Related Questions