开发者

Dynamically remove select form fields inside divs with data taken from php

I have a form with select fields dynamically generated and with the options taken from php (same for all the selects). The "add" button is working but the "remove" button is not working perfectly, it´s not deleting everything and if you add again, it goes below the ideal position.

This is the code that I have:

<script type="text/javascript">
//<![CDATA[ 
$(function(){
var counter = 1;

$("#addButton").click(function () {

if(counter>10){
        alert("Only 10 textboxes allow");
        return false;
}   

var select = $('<select>').attr({id:'select'+counter,name:'select'+counter});

$.ajax({
url: 'selects.php',
dataType: "html",
success: function(data) {
select.html(data);
}
});        

select.appendTo("#TextBoxesGroup");
$("#TextBoxesGroup > select").wrap ( function () {
return '<div id="wrap_' + this.id + '"></div>';
} ); 
counter++;
});

$("#removeButton").click(function () {
 if(counter==1){
      alert("No more textbox to remove");
      return false;
 }   

 counter--;

     $("#wrap_" + counter).remove();
     $("#select" + counter).remove();

 });

});
//]]> 
</script>

<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
    <label>Textbox #1 : </label><input type='text' id='textbox1' >
</div>
<div id="TextBoxDiv2">
    <label>Textbox #2 : </label><input type='text' id='textbox2' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>

And this is the html code generated by select.php:

<option value="1">Uno</option>
<option value="2">Dos</option>
<option value="3">Tres</option>
<option value="4">开发者_StackOverflow中文版Cuatro</option>


the problem ids this when you return

return '<div id="wrap_' + this.id + '"></div>'  

this.id is select's id

but when you are removing

 $("#wrap_" + counter).remove();

try to remove by

  $("#wrap_select" + counter).remove();

because your div's id is

wrap_select+'some value' not wrap_+'some value'


As the other 2 answers said, the problem is:

$("#wrap_" + counter).remove();

Change it to:

$("#wrap_select" + counter).remove ();

To match how the wrap-div was created.

See it in action at jsFiddle.


The selects get the id 'select'+counter, and the wrappers get the id 'wrap_' + this.id, and this.id is, if I'm not too morning tired, not the same as the counter.

And since you're doing this

 $("#wrap_" + counter).remove();
 $("#select" + counter).remove();

You're not removing the wrapper.


0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜