【发布时间】:2020-03-31 05:13:13
【问题描述】:
在我的 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>
感谢您的帮助
【问题讨论】:
-
那个函数
load在何时何地被调用......? -
如果复选框在提交后保持正确选中状态,您可以在页面重新加载时检查其状态并相应地设置文本框可见性。
-
@04FS 在 body-element
onload = "load()" -
@David 如何在 JS 中编写“页面重新加载时”?使用 `var other = document.getElementById('other'); var otherText = document.getElementById('otherValue'); if (other.checked){ otherText.style.visibility = 'visible'; } else { otherText.style.visibility = '隐藏'; }' 没有任何反应...
标签: javascript jquery html forms session-storage