如何保留输入值时,复选框被选中Javascript?



如何保留对应复选框被选中的输入框的值,如果对应的复选框未被选中则从form清除输入值?

<form onsubmit="finalSubmission">
<input type="checkbox" id="yourBox1" />
<input type="text" id="yourText1" />
<br>
<hr>
<input type="checkbox" id="yourBox2" />
<input type="text" id="yourText2" />
<br>
<hr>
<input type="checkbox" id="yourBox3" />
<input type="text" id="yourText3" />
<br>
<hr>
<input type="checkbox" id="yourBox4" />
<input type="text" id="yourText4" />
<br>
<hr>
<button type="submit">Submit</button>
</form>

我知道我可以这样做,但是有其他的方法吗?这是一个相当长的方法

function finalSubmission(event){
event.preventDefault();
let firstInputField;
let checkBox1 = document.getElementById("yourBox1");
if (checkBox1.checked == true){
firstInputField = true
} else {
firstInputField = false
}
if(!firstInputField){
document.getElementById('yourText').value = "";
}
}

试试这个-

function finalSubmission() {
for (var i = 0; i < 4; i++) {
!document.getElementById("yourBox" + i).checked ? document.getElementById("yourText" + i).value = "" : null;
}
}
<input type="checkbox" id="yourBox1" />
<input type="text" id="yourText1" />
<br>
<hr>
<input type="checkbox" id="yourBox2" />
<input type="text" id="yourText2" />
<br>
<hr>
<input type="checkbox" id="yourBox3" />
<input type="text" id="yourText3" />
<br>
<hr>
<input type="checkbox" id="yourBox4" />
<input type="text" id="yourText4" />
<br>
<hr>
<button type="submit" onclick="finalSubmission">Submit</button>

最新更新