如何在html和JavaScript中的按钮前插入文本框



我想在按钮之前插入文本框,我试图操作insertBefore,但无法完成。

function addTextBox() {
const textBox = document.createElement("INPUT");
textBox.setAttribute("type", "text");
const field = document.getElementById("field");
field.appendChild(textBox);
var plus = document.getElementById("plus");
field.insertBefore(textBox, plus);
}
<div class="mydiv">
<form action="Education.html">
<fieldset id="field">
<header>Interests Section</header>
<label for="iname">Interests</label>
<input type="text" id="iname" placeholder="Descripe your interest..." name="name"><br><br>
<input type="button" id="plus" onclick="addTextBox()" class="plus" value="+ new interest..." name="plus" />
<input type="submit" class="hov" style="margin-top:80%" value="Next">
</fieldset>
</form>
</div>
<footer>
Copyright&copy;2022 Rami Joulani
</footer>

如果你想堆叠它们,我想我就是这样做的。我在您的字段集中放置了一个DIV,以便它首先出现在按钮之前。

function addTextBox() {
const textBox = document.createElement("INPUT");
const lbreak = document.createElement("br");
textBox.setAttribute("type", "text");
textBox.setAttribute("Placeholder","More interest");


const field = document.getElementById("addtextbox");

field.appendChild(textBox);
field.appendChild(lbreak);

}
<div class="mydiv">
<form action="Education.html">
<fieldset id="field">
<h1>Interests Section</h1>
<label for="iname">Interests</label>
<input type="text" id="iname" placeholder="Describe your interest..." name="name"><br><br>
<div id="addtextbox"></div><br>
<input type="button" id="plus" onclick="addTextBox()" class="plus" value="+ new interest..." name="plus" >
<input type="submit" class="hov"  value="Next">
</fieldset>
</form>
</div>

最新更新