显示/隐藏具有下拉选项的div

时间:2018-07-06 19:11:01

标签: javascript jquery html

JS相对较新,需要一些帮助以使div根据下拉选项正确隐藏/显示。

如果dropdown ='no',则div应该被隐藏。如果dropdown ='yes',则div应该显示。首先,我让JS正常工作,但是一旦保存表单并重新打开它,div就会消失。我相信我通过告诉div仅在更改时显示JS写错了JS。但是我太新了,不知道-帮助!

$('.analysisPub').on('change', function() {
  if (this.value === "Yes") {
    $("#analysis").show();
  } else {
    $("#analysis").hide();
  }
});
.analysis {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Does this publication include analysis in any form?</td>

    <td class="analysisPub" id="analysisPub" name="analysisPub">
      <select>
        <option value>Yes</option>
        <option value>No</option>
      </select>
    </td>
  </tr>
</table>

<div id="analysis" class="analysis">

  <table>
    <tr>
      <td>Test Name</td>
      <td>Test 1</td>
      <td>Test 2</td>
    </tr>
  </table>
</div>

1 个答案:

答案 0 :(得分:0)

您的代码中有两个主要错误。它们如下-

1st - you were targetting the <td> rather than the <select>

2nd - your dropdown options were not having values

我已经修复了它们。就像您在说明中提到的那样。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
    $('#dropdownAnalysis').on('change', function() {
      if (this.value == 'Yes')
      {
        $("#analysis").show();
      }
      else
      {
        $("#analysis").hide();
      }
    });
});
</script>

<table>
  <tr>
    <td>Does this publication include analysis in any form?</td>
    <td class="analysisPub" id="analysisPub" name="analysisPub">
     <select id="dropdownAnalysis">
        <option value="Yes">Yes</option>
        <option value="No">No</option>
      </select>
    </td>
  </tr>
</table>

<div id="analysis" class="analysis">
  <table>
    <tr>
      <td>Test Name</td>
      <td>Test 1</td>
      <td>Test 2</td>
    </tr>
  </table>
</div>