2014-04-25 47 views
-1

刪除字段我有這樣的代碼:http://jsfiddle.net/spadez/975VQ/3/添加字段,並與jQuery

我希望能夠有一個輸入框開始,完成與選擇字段和刪除按鈕,並能夠動態地將其刪除,並添加更多。

這是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

由於'變種Add按鈕= $( 「#激活addField」);'你有,你不需要使用$(AddButton)....只是AddButton將工作.... –

+1

是這樣的? http://jsfiddle.net/Alfie/975VQ/12/ – Anton

+0

是的,就像那個 – Jimmy

回答

3

你錯過添加id在您的網頁試試這個你html elementsjquery

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; 
    }); 
}); 

Demo

更新Demo with maxinputs

2

這不工作的原因是因爲你的兩個變量InputsWrapperAddButton的。這兩個變量是空的,因爲沒有有InputsWrapperAddField作爲一個ID屬性

以下是更正HTML的任何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