javascript - 选中复选框时保持表单文本输入的可见性
问题描述
在我的 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
解决方案
使用道具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>
推荐阅读
- c - STM32F4 作为 I2C 从设备。为什么在“HAL_I2C_Slave_Transmit_DMA”之后执行“void I2C1_ER_IRQHandler(void)”?
- java - 如何在 RecyclerView 中为自定义视图使用 setter?
- ruby - Cucumber - “您没有‘功能’目录。请创建一个以开始使用”消息
- sql - 甲骨文:LAST_VALUE 与 FIRST_VALUE
- docker - Docker Compose 网络多播
- powerbi - Power BI 层次结构表视觉对象
- c# - 过滤相关实体的值(asp.net 核心)
- python - 选中/取消选中时获取复选框以创建/删除窗口
- javascript - 组合输入并选择输入/更改
- vb.net - Access 动态创建的 UserControl 的 Public Declare - WinForms