簡體   English   中英

單擊 onclick 按鈕時如何添加新表單或 div

[英]How do you add a new form or div when a onclick button is clicked

我有一個表單,要求用戶輸入房間號和價格,如下圖所示。

在此處輸入圖像描述

如果用戶想要,他們可以點擊一個按鈕來顯示一個新的表單,然后他們可以添加新的房間號和價格。 它看起來像這樣,但我對它們進行了硬編碼。

在此處輸入圖像描述

您如何制作 JS function 來做到這一點?

另外,我想通過用戶單擊提交按鈕將這些值設置到我的 firebase 實時數據庫中,但是如果用戶單擊“添加更多房間”按鈕,新創建的表單是否會引用不同的表單 ID?

更新:包括我的代碼。

 <div>
    <form class="specify-numbers-price">
        <label for="ask-room-numbers-price">Please specify the room number and its price: </label>
        <br>
        <label for="room-numbers">Room numbers: </label>
        <input type="number" id="room-numbers" name="room-numbers" min="0" max="1000" >
        <label for="room-price">  Price (in $): </label>
        <input type="number" id="room-price" name="room-price" min="0">
        <br>
        <button type="submit" id="add-more-rooms" >Add more rooms</button>
    </form> 
</div>

每次單擊其按鈕時,該要求似乎都在復制現有表單。

如果這是要求,這將向父 div 添加一個新表單:

 const div = document.getElementById('form-wrapper'); function duplicateForm() { let forms = div.getElementsByClassName('specify-numbers-price'); let firstForm = forms[0]; let formClone = firstForm.cloneNode(true); div.appendChild(formClone); }
 <div id="form-wrapper"> <form class="specify-numbers-price"> <label for="ask-room-numbers-price">Please specify the room number and its price: </label> <br> <label for="room-numbers">Room numbers: </label> <input type="number" id="room-numbers" name="room-numbers" min="0" max="1000"> <label for="room-price"> Price (in $): </label> <input type="number" id="room-price" name="room-price" min="0"> <br> <button type="button" id="add-more-rooms" onclick="duplicateForm();">Add more rooms</button> </form> </div>

這已經是之前討論過的內容,只需使用內部 html 並通過 id 或 class 獲取 div 元素...我將向您展示一個簡單的示例,您必須在 Z686155AF75A60A0F6E9D80C1FF7EDD 中執行此操作。

 /** * A little example */ function addRow(newDivId) { let mydiv = document.getElementById("divId"); //This is a global div that contains others dynamic divs. mydiv.innerHTML = `<div id='{newDivId}'>This is a new div with a diferent id</p>`; } function removeRow(idToRemove) { document.getElementById(idToRemove).remove(); }

暫無
暫無

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

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