使用jQuery显示/隐藏字段

x8goxv8g  于 2023-05-28  发布在  jQuery
关注(0)|答案(2)|浏览(203)

单击“是”后单击“否”时,是否可以隐藏“请指定...”字段?

$(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>
w1jd8yoj

w1jd8yoj1#

只需委派和切换

$(function() {
  var policeInvolvedYes = $('input[name="policeInvolved"][value="yes"]');
  var policeDetailsGroup = $('#policeDetailsGroup');
  var policeDetails = $('#policeDetails');

  const updatePoliceDetailsField = () => {
    const show = policeInvolvedYes.is(':checked');
    policeDetailsGroup.toggle(show);
    policeDetails.prop('required', show);
  };

  $('.radio').on('change', '[name=policeInvolved]', 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>If yes, please specify:
  <input type="text" class="form-control" id="policeDetails" name="policeDetails" placeholder="Enter details"></label>
</div>
taor4pac

taor4pac2#

$(function() { var policeInvolvedYes = $('input[name="policeInvolved"][value="yes"]'); var policeDetailsGroup = $('#policeDetailsGroup'); var policeDetails = $('#policeDetails');

相关问题