Pregunta

I've wrote the code bellow in order to add a new <li> embedded form using jQuery on click event on an input button. This actualy works for a Symfony2 Formbuilder view.

Now I need to write the reverse function to delete a <li>. I've tried a simple .remove() on the <li> id, but it doesn't work. It seems to be a bit more complicated than this.

 $(function(){
     var index = 0;
     var prototype = $('ul.answers').data('prototype');
     $('#addmore').on('click', function(){
            var newForm = prototype.replace(/__name__/g, index++);
            var newLi = $('<fieldset><legend>Answer '+index+' :</legend><li id="answer'+index+'"></li>\n\
<input id="removeone" type="button" value="Delete this answer"></fieldset>');

        newLi.append(newForm);
        $(this).before(newLi);
     });

     $('#removeone').on('click', function(){
            $( "#answer"+index).remove;            
     });

 });

 <ul class="answers" data-prototype="{{ form_widget(form.answers.vars.prototype)|e }}">
    {% for answer in form.answers %}
        <li style="display:none;">{{ form_row(answer.answer) }}
        {{ form_row(answer.feedback) }}
        </li>
    {% endfor %}        
 </ul>
 <input id="addmore" type="button" value="Add an answer">
¿Fue útil?

Solución

$( function() {
    $( ".answers li" ).on( "click", function() {
        $( this ).remove();
    });
});

That should do the work ; maybe this will not run with dynamically added content, you may try this alternative (and add a class to your li elements ) :

$( function() {
    $( document ).on( "click", ".liClass", function() {
        $( this ).remove();
    });
});

Otros consejos

Try

$(document).on('click','#removeone' ,function(){
   $(this).prev('[id=^"answer"]').remove();            
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top