选择后 Div 不显示

问题描述 投票:0回答:1

由于某种原因,我可以显示框和所有内容,但每次我在选择选择后尝试显示 DIV 时,什么也没有发生......请建议。

$(document).ready(function () {
    var divs = document.getElementById('showRef');
    divs.style.display = 'none';
    $('.selRef').on('change', function () {

        var refValid = (this.value == "Yes");
        if (refValid) {
            divs.style.display = 'block';
        }
        else {
            divs.style.display = 'none';
        }
    })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
        <div class="col-md-12">
            <div class="input-group">
                <select id='selRef'
                required runat="server" clientidmode="Static" class="form-control selRef">
                <option value="No" selected>No</option>
                <option value="Yes">Yes</option>
            </select>
            </div>
        </div>
    </div>

</div>
<div id="showRef" runat="server">
<div class="row mt-3">

每次我单击或更改下拉值时,都没有任何反应...

javascript html jquery asp.net
1个回答
0
投票

您距离解决方案并不遥远。您只需使用

selRef.val();

获取选择元素的值

查看下面的代码:

$(document).ready(function () {
  let divs = document.getElementById('showRef');

  // you should define this style in html css
  //divs.style.display = 'none';

  const selRef = $('#selRef');
  selRef.on('change', function () {
    // if you log 'this.value', the script return the window object, this is not what you want
    // you have to get the value of the select element like this :
    const selRefValue = selRef.val();
    if (selRefValue === 'Yes') {
      divs.style.display = 'block';
    }
    else {
      divs.style.display = 'none';
    }
  });
});
body {
  width: 600px;
  margin: auto;
}
#title {
  background-color: darkgreen;
}
h1 {
  text-align: center;
}
#showRef {
  width: 100%;
  min-height: 100px;
  background-color: pink;
}
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
  <div id="title">
    <h1>Hello, this a the test!</h1>
  </div>

  <!-- Here the code to test -->
  <select id='selRef' required>
    <option value="No" selected>No</option>
    <option value="Yes">Yes</option>
  </select>

  <div id="showRef" style="display: none"></div>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.