Simon Otter Simon Otter - 3 months ago 11
HTML Question

Select dependent on Radio Button

How can I make a

<SELECT>
visible if a particular
<INPUT type="radio">
is selected?

I have the following function at the end of
<BODY>
:

<script>
$('[data-dependent]').each(function () {
var $ele = $(this);
var dependsOn = $ele.data('dependent');
$.each(dependsOn, function (target, value) {
$(target).on('change', function () {
if($(this).val() === value) {
$ele.show();
}
else {
$ele.hide();
}
});
});
});
</script>


My HTML is:

<input type="radio" name="itemOption" id="deleteAllItems" value="deleteAllItems">Delete items
<input type="radio" name="itemOption" id="moveAllItems" value="moveAllItems" checked>Move items

<select id="inputCategory" name="category" data-dependent='{"itemOption": "moveAllItems"}'>
<option>Choose a category to move the items to...</option>
<option>Category A</option>
<option>Category B</option>
</select>

Answer

You simply need to replace $(target) with $('[name="'+target+'"]') :

$('[data-dependent]').each(function () {
    var $ele = $(this);
    var dependsOn = $ele.data('dependent');
    $.each(dependsOn, function (target, value) {  
        $('[name="'+target+'"]').on('change', function () {
            $ele.toggle($(this).val() === value);
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" name="itemOption" id="deleteAllItems" value="deleteAllItems">Delete items
<input type="radio" name="itemOption" id="moveAllItems" value="moveAllItems" checked>Move items

<select id="inputCategory" name="category" data-dependent='{"itemOption": "moveAllItems"}'>
   <option>Choose a category to move the items to...</option>
   <option>Category A</option>
   <option>Category B</option>
</select>