如果后端验证失败,jquery仍然需要隐藏表单字段

时间:2017-12-01 12:19:50

标签: jquery

如果早期表单字段中的select值为.time(python backend),我正在使用下面的Jquery只显示带有css类False的表单字段。 (隐藏的是select具有空值false或者用户选择True)。

效果很好,但问题是如果表单验证失败且用户选择了False,则在页面刷新后,.time字段会保持隐藏状态。

我不仅hide()show元素取决于change事件,还依赖于某个值? (即如果值为False,则在页面刷新后如此,那么它也将显示该字段)

$(document).ready(function () {
    $('#id_same_address').on('change',  function (e){
      var timeAtAddress = $(this).val()
      console.log(timeAtAddress)
      if (timeAtAddress === 'False' ){
        $('.time').show()
      }
      if (timeAtAddress === 'True' || timeAtAddress === false){
        $('.time').hide()
      }
    })
  })

只是试图抓住选择值,由于某种原因无法工作?

$(document).ready(function () {
  var timeAtAddress = $('#id_same_address').val()
  console.log(timeAtAddress)
  if (timeAtAddress === 'False') {
    $('.time').show()
  }
  if (timeAtAddress === 'True' || timeAtAddress === false) {
    $('.time').hide()
  }
})

1 个答案:

答案 0 :(得分:0)

这对我来说很好。请记住,您需要将选项设置为选中(默认),以便在文档准备就绪时正确设置字段。

实施例: http://jsbin.com/nopenohomo/edit?html,js,console,output

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script type="text/javascript">
    $(document).ready(function () {
    let dropdown_value = $('#dropdown').val();

    if (dropdown_value === 'true') {
      $('.time').show();
    } else {
      $('.time').hide();
    }

    $('#dropdown').on('change',  function (e){
      var timeAtAddress = $(this).val()
      console.log(timeAtAddress)
      if (timeAtAddress === 'true' ){
        $('.time').show()
      }
      if (timeAtAddress === 'false'){
        $('.time').hide()
      }
    });
  });
  </script>
  </head>
<body>
 <select id="dropdown">
  <option value="true">True</option>
  <option value="false" selected="false">False</option>
</select> 
  <div class="time">
    Test
  </div>
</body>
</html>