0

If I create an element with class in jQuery that element wont include the attached functions.

For example, in below code first of all I am creating 2 different element in html and in (document.ready) I assign the change event this class.

These two elements working properly. However, When click the button, I create a new element which has same class but related event wont work for this element.

Why this happen? and how can I attach all events the new element easily?

Thanks in advance.

My Code:

<body>
    <div class="main">
        <input class="test" value="2" type="text">
        <input class="test" value="3" type="text">
        <input class="button" value="Click" type="button">
    </div>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $('.test').change(function () {
            $('.main').append('<p>Test</p>');

        });
        $('.button').click(function () {
            $('.main').append('<input class="test" value="x" type="text">');

        });

    });
</script>
Gurcan
  • 408
  • 7
  • 17

1 Answers1

2
    $('.button').click(function () {});

only work on the elements while this code was executed.

    $('.button').on('click', function () {});

work on all elements in document(even if it is added later)

andyf
  • 2,928
  • 3
  • 19
  • 35