0

Don't work my jQuery code after append. how can just change js code and worked it?

I don't use from ides "#aaa or #sss", How do without use them?

DEMO: http://jsfiddle.net/sq4kx/

html:

<a href="" class="qqq">Click Me</a>
<div id="aaa">
    <div id="sss">
    </div>
</div>

jQuery:

$('.qqq').on('click', function (e) {
    e.preventDefault();
    $('#sss').empty().append('After typed must result alert: "This is ok" !??<div class="auto_box"><input name="we" class="de1"></div>');
})
$('.auto_box').on('keyup change', '.de1', function () {
    alert('This is ok');
})
Taylor Gomez
  • 320
  • 1
  • 5
  • 22

3 Answers3

1

Try this like,

$('#sss').on('keyup change', '.auto_box .de1', function () {
    alert('This is ok');
});

Demo 1

Or

$('.qqq').on('click', function (e) {
    e.preventDefault();
    $('#sss').empty().append('After typed must result alert: "This is ok" !??<div class="auto_box"><input name="we" class="de1"></div>');    
    // bind event here
    $('.auto_box').on('keyup change', '.de1', function () {
        alert('This is ok');
    });
});

Demo 2

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

Try:

$(document).on('keyup change', '.de1', function () {
    alert('This is ok');
});

Updated fiddle here.

codingrose
  • 15,563
  • 11
  • 39
  • 58
0

replace '.auto_box' with document.

$(document).on('keyup change', '.de1', function () {
    alert('This is ok');
});

Reason:Why the above code works and yours does not?

1.You are dynamically adding elements.In simpler words,the element you appended did not exist when DOM was loaded.

2.You need to assign Event Delegation for any future addition of elements.The method that we usually use like .click(...) , .on(..) etc only applies to the elements that are currently in the DOM.

3.This is how you provide Event Delegation.

$(document).on('keyup change', '.de1', function(){.........})

Community
  • 1
  • 1
HIRA THAKUR
  • 17,189
  • 14
  • 56
  • 87