1

I'm generating a list with buttons for every new element.

This part is in a javascript function generating the list. I've given the button a class called adding. I'm expecting a message when I click on a button. Following other entries and pages about this subject have gotten me this far but I need an extra explanation on what I'm doing wrong.

Part of javascript for list (vehicleList.js):

  ... + '<input class="adding" type="button" name="vehicle" value="Add vehicle">' + ...

Javascript for click (part of html):

<script>
$(function() {
    $('.adding').on('click', '.adding', function(){
        alert('Click detected');
    });
});
</script>

1 Answer 1

1

If you want to use this syntax of code you need to target the document (or parent element) by using something like this:

$(function() {
    $(document).on('click', '.adding', function(){
        alert('Click detected');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="adding">click me</button>

As you can read here:

.on( events [, selector ] [, data ], handler )

..

selector

Type: String

A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.

And this will work for dynamically generated button.

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

2 Comments

I'm still not getting it to work. My for loop is creating the button by adding it to a string which javascript then writes out on html. But I also have a test button which is created with the page and that's also dead.
@AtesTen you tried the first one right ? as it shoud work

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.