-1

So I'm kind of baffled by this problem. I'm duplicating this select when they use it. The goal is to be able more players to a team. If they add one, it creates another select. If they add a second player then a third select is created.

Currently, it's only duplicating whenever the first select is changed. Shouldn't .on() apply to all elements created dynamically after the javascript is parsed and bound? How do I make it so it's only applying to the most recently added select? Thanks in advance for your time!

JQuery

$(document).ready(function(){
    another = $('#addplayers');
    $('.addplayer').on('change', function(){
        another.clone().removeAttr('id').appendTo($(this).closest('.form-horizontal'));
        $(this).removeClass('addplayer');
    });
});

HTML

<div class="form-group" id="addplayers">
                        <label class="col-sm-2 control-label">Add Player</label>
                        <div class="col-sm-10">
                            <select class="addplayer" team="<%=@team.id%>">
                                <%@players.each do |player|%>
                                    <option value="<%=player.id%>"><%=player.name%></option>
                                <%end%>
                            </select>
                        </div>
                    </div>
Aarmora
  • 1,143
  • 1
  • 13
  • 26

1 Answers1

0

You need to apply correct syntax for event delegation using:

$(document.body).on('change', '.addplayer', function(){

instead of:

$('.addplayer').on('change', function(){
Felix
  • 37,892
  • 8
  • 43
  • 55
  • My understanding was that this method was deprecated with the newer versions of jquery. Trying it – Aarmora Apr 14 '14 at 16:39
  • 1
    `.on()` is not deprecated, you just made a mistake in applying it in the correct way. – Felix Apr 14 '14 at 16:41
  • I mean, using `$(document.body).on('change', '.addplayer', function(){` this method of event delegation. – Aarmora Apr 14 '14 at 16:43
  • @Aarmora It's not deprecated at all. – Denys Séguret Apr 14 '14 at 16:45
  • @dystroy Searching for docs now. It's definitely working on my page as is suggested by Felix so I'm just trying to find why I thought that and started doing my code like `.live()` used to be done. – Aarmora Apr 14 '14 at 16:47