我有这段代码:http://jsfiddle.net/spadez/975VQ/3/
我希望能够从输入框开始,完成选择字段和删除按钮,并能够动态删除它们并添加更多内容。
这是我发现并尝试修改的JavaScript jQuery:
$(document).ready(function() {
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#addfield"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(InputsWrapper).append('<div><input type="text" name="mytext[]" id="field_'+ FieldCount +'" value="Text '+ FieldCount +'"/><button class="removeclass">Delete</button></div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
});
它似乎不适用于添加或删除输入框,而且似乎没有任何错误说出原因。
答案 0 :(得分:3)
您错过了在id
和html elements
页面中添加jquery
,请尝试此操作,
<强> HTML 强>
<h1>Questions</h1>
<p>Add additional questions. You can select how long you would like the reply to be.</p>
<div class="add-row">
<input value="Why do you want this" />
<select>
<option value="single">Single line reply</option>
<option value="multi">Paragraph reply</option>
</select>
<button class="remove">Delete</button>
</div>
<br />
<button id="addfield">Add question</button>
<br />
<强> SCRIPT 强>
$(document).ready(function () {
$('#addfield').on('click', function(){
$clone=$('.add-row:first').clone();
$clone.insertAfter($('.add-row:last'));
});
$(document).on("click",".remove", function(e){ //user click on remove text
if( $('.add-row').length > 1 ) {
$(this).closest('div.add-row').remove(); //remove entire row
}
return false;
});
});
答案 1 :(得分:2)
这不起作用的原因是因为您的两个变量InputsWrapper
和AddButton
。这两个变量都为null,因为没有任何HTML将InputsWrapper
或AddField
作为ID属性
以下是更正的HTML:
<h1>Questions</h1>
<p>Add additional questions. You can select how long you would like the reply to be. </p>
<div id="InputsWrapper">
<input value="Why do you want this">
<select>
<option value="single">Single line reply</option>
<option value="multi">Paragraph reply</option>
</select>
<button>Delete</button>
</div>
<button id="addfield">Add question</button>
<强> SEE FIDDLE 强>