首页 > 解决方案 > 选中复选框时保持表单文本输入的可见性

问题描述

在我的 HTML 中,我有一个表单,用户可以在其中选择“其他”复选框,然后出现一个文本框。否则文本框被隐藏。您可以在下面找到我的代码。但是,如果用户选择“其他”,输入他的文本并提交表单,文本框将再次隐藏 - 尽管复选框保持选中状态(保存在 localStorage 中)。我在这里找不到我的错误。

形式:

<label class="form-check">
       <input class="form-check-input" name="filetype" type="checkbox" id="other" value="" onclick="save()">
       <span class="form-check-label"
             <input placeholder="e.g. 'msg'" name="other" onsubmit="save();" class="form-control input-lg" type="text" id="otherValue" value="{{extension}}">
       </span>
</label> <!-- form-check -->

可见/隐藏

 <!--"Other"-filter-->
      <script type="text/javascript">
        var otherCheckbox = document.querySelector('input[id="other"]');
        var otherText = document.querySelector('input[id="otherValue"]');
        otherText.style.visibility = 'hidden';

        otherCheckbox.onchange = function(){
            if(otherCheckbox.checked) {
                otherText.style.visibility = 'visible';
                otherCheckbox.value = otherText.value;
                save();
            } else {
                otherText.style.visibility = 'hidden';
            }
        };
      </script>

试图通过将信息保存在sessionStorage中来解决这个问题,但它仍然不起作用。

 <!--Save Checkbox-State-->
      <script type="text/javascript">
        const checkboxen = [...document.querySelectorAll("[type=checkbox]")].map(inp => inp.id); //list of all checkbox-IDs

        function save(){
            for (var i = 0 ; i< checkboxen.length; i++){
                var id = checkboxen[i];
                var checkbox = document.getElementById(id);
                sessionStorage.setItem(id,checkbox.checked);
            }
            var other = document.getElementById('otherValue');
            sessionStorage.setItem('otherValue',other.style.visibility);
        }
        function load(){
            for (var i = 0 ; i< checkboxen.length; i++){
                var id = checkboxen[i];
                var checked =JSON.parse(sessionStorage.getItem(id));
                document.getElementById(id).checked = checked;
            }
            var other = JSON.parse(sessionStorage.getItem('otherValue'));
            document.getElementById('otherValue').style.visibility = other;
        }
        function deleteCheckbox(){         
            sessionStorage.clear();
        }
       </script>

感谢您的帮助<3

标签: javascriptjqueryhtmlformssession-storage

解决方案


使用道具jquery:

<script>
    $(function(){
       var other = localStorage.input === 'true'? true: false;
       $('input').prop('checked', other);
    });

    $('input').on('change', function() {
       localStorage.input = $(this).is(':checked');
       console.log($(this).is(':checked'));
    });
</script>

推荐阅读