我有两个文本字段和一个复选框。基本上,代码应该发生两件事:
我在下面的代码中实现了它,但是我很确定代码是一团糟。有没有更优雅的方式来解决这个问题?
<script>
document.getElementById('A026_01').onclick = function ClearFields() {
document.getElementById('A025_01').value = "";
document.getElementById('A025_02').value = "";
}
document.getElementById('A025_01').onchange = function ClearFields2() {
document.getElementById('A026_01').checked = false;
}
document.getElementById('A025_02').onchange = function ClearFields2() {
document.getElementById('A026_01').checked = false;
}
</script>
答案 0 :(得分:2)
也许这应该让你高兴...
const chkBx = document.getElementById('A026_01')
, inp_1 = document.getElementById('A025_01')
, inp_2 = document.getElementById('A025_02')
;
// init
chkBx.checked = false
chkBx.onclick=_=>inp_1.value = inp_2.value = ''
inp_1.oninput=_=>chkBx.checked = false
inp_2.oninput=_=>chkBx.checked = false
<input type="checkbox" id="A026_01" />A026_01 <br>
<input type="text" id="A025_01" />A025_01
<input type="text" id="A025_02" />A026_01
答案 1 :(得分:1)
使用 oninput 代替 onchange ,像这样:
document.getElementById('A026_01').onclick = function () {
document.getElementById('A025_01').value = "";
document.getElementById('A025_02').value = "";
}
document.getElementById('A025_01').oninput = function () {
document.getElementById('A026_01').checked = false;
}
document.getElementById('A025_02').oninput = function () {
document.getElementById('A026_01').checked = false;
}
<input type="text" id ="A025_01">A025_01
<br>
<input type="text" id ="A025_02">A025_02
<br>
<input type="checkbox" id ="A026_01">A026_01
答案 2 :(得分:0)
我会做这样的事情: 1.将所有内容保存在变量中; 2.在开始键入(按键)时清除数据。
const checkBox = document.getElementById('A026_01');
const textField1 = document.getElementById('A025_01');
const textField2 = document.getElementById('A025_02');
const unCheck = () => {
checkBox.checked = false;
};
checkBox.addEventListener('click', () => {
textField1.value = '';
textField2.value = '';
});
[textField1, textField2].forEach(textElem => {
textElem.addEventListener('keypress', unCheck);
});