1

I build a small script.

I want to put some fields in and do it with the append function from jquery.

Now every row should have a toggle behind.

It works, but not correctly.

Can anybody help me to do right toggle and after that delete any selected row?

Thank you

var x = 1; //initlal text box count
var max_fields = 5
var add_fields = $(".add_field");
var inputrows = $(".input_rows");
    
$(add_fields).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max 
   x++; //text box increment
        $(inputrows).append('<div class="descriptionrow" id="' + x + '"><div class="remove"><input type="text" name="posten[]" class="in90 posten"><a href="#" class="add_description_field">EX</a><br /><div class="description" style="display:none;">Beschreibung ' + x + '</div></div></div>'); //add input box
 $('.add_description_field').click(function(e){
     $(this).closest('.remove').find('.description').toggle();
 });
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button class="add_field">weitere Position hinzufügen</button><br /><br />

<div class="input_rows"></div>
Julian
  • 1,592
  • 1
  • 13
  • 33
SaschaK
  • 170
  • 2
  • 15

1 Answers1

1

Every time you add a field, you add a click handler to all the .add_description_field links, not just the new one that you just added. So when you click on the older links, this handler is run multiple times. The first time will toggle the description in one way, the second time will toggle it the other way, so they cancel each other out if there are an even number of handlers.

Rather than adding a handler every time you add a field, see Event binding on dynamically created elements? for how to delegate the handler once.

input_rows.on("click", ".add_description_field", function(e){
    $(this).closest('.remove').find('.description').toggle();
});
Barmar
  • 741,623
  • 53
  • 500
  • 612