amazonの様に、住所を複数追加できる様にしたい。
<h1>住所追加</h1> <div > <form> <button id="btn1" type="button" onclick="clickBtn1()">住所を追加する</button> <div id="address1"> <input type="text" name="zipcode_1" value="" placeholder="郵便番号"><br> <input type="text" name="address1_1" value="" placeholder="住所1"><br> <input type="text" name="address2_1" value="" placeholder="住所2"><br> </div> </form> </div> <script> document.getElementById("address1").style.display = "none"; function clickBtn1(){ const address1 = document.getElementById("address1"); if(address1.style.display=="block"){ document.getElementById("btn1").textContent = "住所を追加する"; document.getElementsByName("zipcode_1").value = ""; document.getElementsByName("address1_1").value = ""; document.getElementsByName("address2_1").value = ""; address1.style.display ="none"; } else{ document.getElementById("btn1").textContent = "追加しない"; address1.style.display ="block"; } } </script>
ここに更に住所を追加するボタンを加える。
– buttonではなく、spanタグにして少しスタイリングする
– 住所1を閉じる時は、住所2を初期化する必要がある
<h1>住所追加</h1> <div > <form> <span id="btn1" onclick="clickBtn1()">住所を追加する</span> <div id="address1"> <input type="text" name="zipcode_1" value="" placeholder="郵便番号"><br> <input type="text" name="address1_1" value="" placeholder="住所1"><br> <input type="text" name="address2_1" value="" placeholder="住所2"><br><br> <span id="btn2" onclick="clickBtn2()">住所を追加する</span> </div> <div id="address2"> <input type="text" name="zipcode_2" value="" placeholder="郵便番号"><br> <input type="text" name="address1_2" value="" placeholder="住所1"><br> <input type="text" name="address2_2" value="" placeholder="住所2"><br><br> </div> </form> </div> <script> document.getElementById("address1").style.display = "none"; document.getElementById("address2").style.display = "none"; function clickBtn1(){ const address1 = document.getElementById("address1"); if(address1.style.display=="block"){ // 住所1 document.getElementById("btn1").textContent = "住所を追加する"; document.getElementsByName("zipcode_1").value = ""; document.getElementsByName("address1_1").value = ""; document.getElementsByName("address2_1").value = ""; address1.style.display ="none"; // 住所2 document.getElementsByName("zipcode_2").value = ""; document.getElementsByName("address1_2").value = ""; document.getElementsByName("address2_2").value = ""; document.getElementById("address2").style.display = "none"; document.getElementById("btn2").textContent = "住所を追加する"; } else{ document.getElementById("btn1").textContent = "追加をやめる"; address1.style.display ="block"; } } function clickBtn2(){ const address2 = document.getElementById("address2"); if(address2.style.display=="block"){ document.getElementById("btn2").textContent = "住所を追加する"; document.getElementsByName("zipcode_2").value = ""; document.getElementsByName("address1_2").value = ""; document.getElementsByName("address2_2").value = ""; address2.style.display ="none"; } else{ document.getElementById("btn2").textContent = "追加をやめる"; address2.style.display ="block"; } } </script>
OK! これを実装する