Question

I have two forms : one is active (opacity 1) and the other is inactive (opacity 0.5 applied to form:last-child). Clicking on the inactive form makes it become active and creates another inactive form after it.

To sum up, I'm having trouble appending html after my last element by clicking on this last element. jQuery keeps selecting the same element instead of using new last elements.

HTML :

<form class="traveler traveler1">
    <h3>Traveler #1</h3>
    <input type="text" placeholder="First name">
    <input type="text" placeholder="Last name">
    <input type="text" placeholder="Birth date">
    <input type="text" placeholder="Passport number">
</form>
   <form class="traveler traveler2">
    <h3>Traveler #2</h3>
    <input type="text" placeholder="First name">
    <input type="text" placeholder="Last name">
    <input type="text" placeholder="Birth date">
    <input type="text" placeholder="Passport number">
</form>

jQuery :

$(function(){
    function addTraveler(){
        $number = $('.traveler').length;
        $number++;
        $('form.traveler').last().after('<form class="traveler traveler' + $number + '"><h3>Traveler #' + $number + '</h3><input type="text" placeholder="First name"><input type="text" placeholder="Last name"><input type="text" placeholder="Birth date"><input type="text" placeholder="Passport number"></form>');
    }

    $('.traveler').last().on('click', function(){
        $('form.traveler').last().after(addTraveler);
    });
})

I can create new forms by clicking on the 2nd form (which is the old last form), but it doesn't work when I click on new last forms.

I've been trying for a few hours now, any assistance would be much appreciated :)

Was it helpful?

Solution

You need to delegate your click event to your dynamically created elements

LIVE DEMO

Let's say all your forms are inside #container

$('#container').on('click', ".traveler:last", addTraveler);

you don't need to use again .after() cause your addTraveler function does all that for you already.

About the .on() method event delegation you can ready more here (Direct and delegated events)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top