简体   繁体   中英

remove() is working on only first div not on rest dynamically added fields

I am trying to remove the HTML field but remove is not working on dynamically added fields.

 $('.delete-ques').on('click', function() { 
            alert('hello');
            $(this).parent().remove(); 
            return false;
            });

https://jsfiddle.net/gp2gwana/3/

Try to add div and remove

You need event delegation for attaching events to dynamically added elements:

$('#clone-ques').on('click','.delete-ques', function() { 
        alert('hello');
        $(this).parent().remove(); 
        return false;
});

Working Demo

do this

$('body').on('click', '.delete-ques', function() {
    // do something
});

You will find some good example

here and here

Use document.on click event for delete on dynamically added elements:

.on used for single handler for all elements that match your selector, including the ones created dynamically.

Demo : https://jsfiddle.net/7s05cdoy/

$(document).on('click','.delete-ques',function() {
      $(this).closest('.parent-question').remove();  // using closest you can get parent of this link
      return false;
    });

You may used $(doument)

$(document).on('click','.delete-ques', function() { 
            alert('hello');
            $(this).parent().remove(); 
            return false;
 });

Your working code https://jsfiddle.net/gp2gwana/5/

Everything is perfect in your code. except below line

$('#select-question'+i).selectize({create: true});

Try your existing code by commenting above line of code.

I seen an error in console

Uncaught TypeError: $(...).selectize is not a function

Edit

You should below line of code before return false inside

$('.delete-ques').on('click', function() { 
        $(this).parent().remove(); 
        return false;
});

Try updated jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM