0

I've got some troubles with this code.

    $('body').on("keypress", ".message", function(e) {
      if ( e.keyCode == 13 && $(".message").val().length > 0 ) {

          input = $(".message");
          // Check for join command.
          if (input.val().substr(0, 5) == "/join") {

            // Get channel
            channel = input.val().substr(7, input.val().length);

            // APPEND NEW TAB
            $("ul.nav-tabs li").after('<li><a href="#' + channel + '" aria-controls="#' + channel + '" role="tab" data-toggle="tab">#' + channel + '</li>');
            $('.tab-content').append('<li class="tab-pane log" role="tab-pane" id="' + channel + '" data-channel="' + channel + '"><div class="Topic">Hej och välkommen till #' + channel + '.</div><ul class="Messages"></ul><input type="text" name="message" id="message" autocomplete="off" class="message sendValue"></li>');
            $(".nav-tabs li").children('a').last().click();
          }


          log('<strong>Du</strong>: ' + input.val());
          send( input.val() );

          $(".message").val('');
        }
      });

The keypress event doesn't react on the dynamically added input, I read something about adding the on event after added, because of that this code runs when the dom is loaded.

So my question is: how can I make this so the dynamic inputs works aswell?

Stubborn
  • 995
  • 4
  • 17
  • 30
Tommy
  • 667
  • 1
  • 10
  • 25
  • This has been already addressed by the following question: http://stackoverflow.com/questions/15090942/jquery-event-handler-not-working-on-dynamic-content –  Nov 22 '15 at 18:48
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Kristján Nov 22 '15 at 18:49
  • @AlbertCyberhulk but he's already using `.on` so that's not the same problem.... – David Zorychta Nov 22 '15 at 18:51

1 Answers1

1

You're already using .on so I think it is working properly and that your real problem is this:

input = $(".message");

which you need to change to this:

var input = $(this);

otherwise you'll always be dealing with the first input even if there's multiple on the page. Also you can use inspect element > console to debug these problems easier. For example if you add:

$('body').on("keypress", ".message", function(e) { console.log(e);

to your script you would have seen that the event handler is working fine and that your problem was further down.

(also change $(".message").val(''); to input.val('');)

David Zorychta
  • 13,039
  • 6
  • 45
  • 81