How can we preserve the value of the input box whose corresponding checkbox is checked, and if the corresponding checkbox is not checked then clear input value from 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>
I know I can do this way, but is there any other alternative approach for this. This is quite a length approach
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 = "";
}
}
Try this -
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.