1

I have this .append function which generates a button for every element:

.append('<button type="button" id="add">Hinzufügen</button>')

Then i have this function which should do something when I click on the button above. The function works on a button which is not "appended".

$(document).ready(function () {
   $("#add").on("click", function () {
      alert("Test");
    });   
});

Does anyone know, why this doesn't work?

2
  • First of all, IDs are not intended to be used on multiple elements, use a class for this. Commented Jan 9, 2022 at 11:24
  • Write your jquery after appending and your buttons with dynamic ids or a class instead please Commented Jan 9, 2022 at 11:24

1 Answer 1

1

A page can't be manipulated safely until the document is ready. jQuery detects this state of readiness and allows you to use ready(). The code included inside $( document ).ready() will only run once the Document Object Model (DOM) is ready for JavaScript code to execute.

You are probably appending the button after this code is being executed.

Another issue you should probably fix is making the id's attributes unique.

More about ready() here

Sign up to request clarification or add additional context in comments.

3 Comments

I have my ready funtion above everything. Could that be the problem then?
No, you will have to attach the listeners to newly created Elements after you have created them, not through the ready fn
@GRIV document readiness removes the need of ordering your js code. It might be related to the event delegation. As jquery on method attaches to the presently existing elements. refer this - api.jquery.com/on

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.