0

I was trying to execute a jquery code in jsfiddle. My jquery code is given below

$(function() {
    var scntDiv = $('#p_scents');
    var i = $('#p_scents p').size() + 1;

    $('#addScnt').on('click', function() {
            $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
            i++;
            return false;
    });

    $('#remScnt').on('click', function() { 
        alert("sfdrijg");
            if( i > 2 ) {
                    $(this).parents('p').remove();
                    i--;
            }
            return false;
    });
});

My HTML code is given below.

<h2><a href="#" id="addScnt">Add Another Input Box</a></h2>

<div id="p_scents">
<p>
    <label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" /></label>
</p>
</div>

My Page Looks like this

Page designed

The click of the "Add Another Input Box" always works whereas the "Remove" does not respond at all.

Manesh
  • 586
  • 3
  • 14
  • 31

3 Answers3

4

Try to change your code to

$(document).on('click','#remScnt', function() {

Refer This is a good answer for more details. https://stackoverflow.com/a/8752376/1640577

Community
  • 1
  • 1
Jithin Lukose
  • 344
  • 4
  • 18
1

Working Demo : JsFiddle

I. Your code will create multiple ids with the same name remScnt which is not right. You have to add class of that element say class="remScnt"

An id must be unique in a page. Use a class if you want to describe a group of elements.

Reason :- Your code will not be valited by W3C, what means that you can have headaches with your website's compability accross browsers. It can works fine in one browser and in other not.

So try to add unique ids for the element.

II Also you have to change your code like below :

$(document).on('click','.remScnt', function() { /* Code goes here */ });

Reason : Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). Your dynamically added element doesn't exist when you call $.on() on it, so the event isn't bound.

Try this code :

$(document).on('click','.remScnt', function() { 
    alert("sfdrijg");
        if( i > 2 ) {
                $(this).parents('p').remove();
                i--;
        }
        // you don't need to add return false            
});
Rakesh Shetty
  • 4,548
  • 7
  • 40
  • 79
0

You haven't provided the html code for your Remove button.

Anyhow, if the your Remove button is the direct child of the

element you're trying to remove, you should use .parent(). It should work just fine. And you don't need to return anything.

so:

$('#remScnt').on('click', function() { 
    alert("sfdrijg");
        if( i > 2 ) {
                $(this).parent().remove();
                i--;
        }
});
user3885269
  • 51
  • 1
  • 1