0

The keyup event is not working for dynamically added id attribute. My code,

HTML

<div id="more-package-div" class="more-package-area">
    <input type="text" name="package_weight[]" id="package_weight_0" placeholder="Package weight" class="package_weight">
</div>
<div id="extra-packages"></div>
<a href="#" id="add-more-package">Add more package</a>

JQUERY

var count = 1;
var i = 0;
$('#add-more-package').on('click', function(){
    $('#extra-packages').append($('#more-package-div').html());
    $('#package_weight_'+i).attr('id','package_weight_'+count);
    i+= 1;
    count += 1;
});

$('.package_weight').on('keyup', function(){
    alert(this.id);
});

In this case the keyup event is only working for the first textbox. How can I trigger the 'keyup' event for dynamically added attributes ?

This is my JSFiddle

Vinod VT
  • 6,946
  • 11
  • 51
  • 75
  • Use event delegation. [`$('#extra-packages').on('keyup', '.package_weight', function () {`](http://jsfiddle.net/tusharj/x749740m/3/) – Tushar Nov 10 '15 at 06:18

1 Answers1

1
var count = 1;
var i = 0;
$('body').on('click','#add-more-package', function(){
    $('#extra-packages').append($('#more-package-div').html());
    $('#package_weight_'+i).attr('id','package_weight_'+count);
    i+= 1;
    count += 1;
});

$('body').on('keyup','.package_weight', function(){
    alert(this.id);
});

DEMO

Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
  • Don't need to delegate the event up to the body, use static parent `#extra-packages` – Tushar Nov 10 '15 at 06:19
  • @Tushar there is more ways $('body') or static parent or even $(document) ... I really didn't searching before about the deference between all of this .. but anyway all of that working with me .. I know you are a very good one in that field .. and appreciate your comment .. and I wiil looking for the deference .. Thanks – Mohamed-Yousef Nov 10 '15 at 06:22