Is it possible to hide the ‘Please specify…’ field when I click ‘No’ after clicking ‘Yes’?
$(document).ready(function() {
var policeInvolvedYes = $('input[name="policeInvolved"][value="yes"]');
var policeDetailsGroup = $('#policeDetailsGroup');
var policeDetails = $('#policeDetails');
function updatePoliceDetailsField() {
if (policeInvolvedYes.is(':checked')) {
policeDetailsGroup.show();
policeDetails.prop('required', true);
} else {
policeDetailsGroup.hide();
policeDetails.prop('required', false);
}
}
policeInvolvedYes.on('change', updatePoliceDetailsField);
updatePoliceDetailsField();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="form-group">
<label>Were Police/Emergency Services involved?</label>
<div class="radio">
<label>
<input type="radio" name="policeInvolved" value="yes"> Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="policeInvolved" value="no"> No
</label>
</div>
</div>
<div id="policeDetailsGroup" style="display: none;">
<label for="policeDetails">If yes, please specify:</label>
<input type="text" class="form-control" id="policeDetails" name="policeDetails" placeholder="Enter details">
</div>
2
Answers
Just delegate and toggle
$(function() { var policeInvolvedYes = $(‘input[name="policeInvolved"][value="yes"]’); var policeDetailsGroup = $(‘#policeDetailsGroup’); var policeDetails = $(‘#policeDetails’);