1

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

Bhawna
  • 705
  • 2
  • 11
  • 28
  • 1
    Possible duplicate: http://stackoverflow.com/questions/19371141/jquery-on-isnt-binding-click-events-to-dynamically-created-elements – ste2425 May 19 '16 at 10:05
  • see this https://jsfiddle.net/gp2gwana/4/. Use event delegation technique for attaching events to dynamically created DOM element. – vijayP May 19 '16 at 10:05
  • `$('#clone-ques').on('click','.delete-ques', function() { ` – Rayon May 19 '16 at 10:05

5 Answers5

3

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

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
2

do this

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

You will find some good example

here and here

Community
  • 1
  • 1
Ranjit Singh
  • 3,715
  • 1
  • 21
  • 35
1

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;
    });
Jayesh Chitroda
  • 4,987
  • 13
  • 18
0

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/

Ankur Bhadania
  • 4,123
  • 1
  • 23
  • 38
0

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

Jitendra Tiwari
  • 1,651
  • 3
  • 14
  • 28