簡體   English   中英

選中復選框時如何保留輸入值 Javascript?

[英]How to preserve input value when checkbox is checked 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM