您好我发现此代码使用javascript添加表单元素
var counter = 1;
var limit = 9;
function addFp(spanName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newspan = document.createElement('span');
newspan.innerHTML = "<br><b>Implement " + (counter + 1) + " : </b></td><select
name='fp_imp"+(counter+1)+"' class=''><option value='imp1'>Disc Harrow</option><option
value='imp2'>Cultivator</option><option value='imp3'>Disc Harrow</option></select> <input type='text'
name='fp_h"+(counter+1)+"' placeholder='Hours' class='' size='4'> <input type='text' name='fp_t"+(counter
+1)+"' placeholder='Times' class='' size='4'>"
document.getElementById(spanName).appendChild(newspan);
counter++;
}
}
此代码的Html是
<script src="assets/js/field_preparation.js"></script>
<div class="form-top">
<div class="form-top-left">
<h3>Step 1 / 9</h3>
<p>Field preparation:</p>
</div>
<div class="form-top-right">
<i class="fa fa-user"></i>
</div>
</div>
<div class="form-bottom">
<div class="form-group">
<table>
<tr><td><b>Tractor Horse Power </b></td><td><b> :</b> </td><td><input type="text" name="tractor" placeholder="HP" class="" size="4"></td></tr>
<tr><td><b>No. of Man Hours </b></td><td> <b> : </b></td><td><input type="text" name="fp_hum" placeholder="Men" class="" size="4"></td></tr>
</table>
<span id="dynamicFp">
<tr><td><b>Implement 1</td><td> : </b></td><td><select name="wheat_imp1" class="">
<option value="imp1">Disc Harrow</option>
<option value="imp2">Cultivator</option>
<option value="imp3">Disc Harrow</option></select>
<input type="text" name="wheat_h1" placeholder="Hours" class="" size="4">
<input type="text" name="wheat_t1" placeholder="Times" class="" size="4">
</span>
<input type="image" src="./assets/img/plus.png" border="0" width="30px" value="Add Implement" onClick="addFp('dynamicFp');">
我遇到的问题是,如果我不需要它,我想要一个代码删除该字段,因为将字段留空将不接受该表单。 所以,任何人都可以为我提供代码以及如何使用它来删除元素。对不起,我是javascript的新手,对代码一无所知。感谢。
答案 0 :(得分:0)
那么,如果用户没有输入字段,你想在表单提交过程中删除这些字段吗?
试试这个
function removeEmptyFields()
{
$("input[name^='fp_h'], input[name^='fp_t'], select[name^='fp_imp']").each(function(){
var $thisObj = $(this);
!$thisObj.value && $thisObj.remove();
})
}
答案 1 :(得分:0)
您要删除最后一个addes元素吗? 在JS
的顶部添加新变量var lastAdded;
var counter = 1;
var limit = 9;
修改addFp,使其记住上次添加的范围
document.getElementById(spanName).appendChild(newspan);
counter++;
lastAdded = newspan;
添加新功能
function deleteLastAdded () {
if (lastAdded) {
lastAdded.remove();
}
}
添加新按钮
<input type="image" src="./assets/img/plus.png" border="0" width="30px" value="Add Implement" onClick="addFp('dynamicFp');">
<button width="30px" value="Delete last added" onClick="deleteLastAdded();">
这里是whole code
编辑:顺便说一下打算打破行,打破行,我把它固定在bin