gpt4 book ai didi

javascript - 选中复选框时保持表单文本输入的可见性

转载 作者:行者123 更新时间:2023-12-01 00:23:30 25 4
gpt4 key购买 nike

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

表格:

<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

最佳答案

prop 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>

关于javascript - 选中复选框时保持表单文本输入的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59209252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com