0

I have a system that generates multiple address fields according the an amount selected by the user.

Initially I used $("input[name=inputname]") which works fine for the initially loaded fiedls but doesn't work when adding more. Searching google and here led me to believe I could use JQuery's .on function, although I can't seem to get it working, is there anything wrong with this code or do I need to approach this a different way?

$("div.data").on( "change", "input[name^=delivery-address-1]", function() {
  alert( $( this ).val() );
});

Thanks in advance

EDIT: Hi, regarding the 'marked as duplicate', as I said I have read the similar answers and am aware of them, but the code learned from these answers doesn't seem to work in my situation and so was looking for further help, thanks.

user1952067
  • 97
  • 1
  • 8

2 Answers2

1

Try using document and not 'div.data' like so:

$(document).on("change", "input[name^=delivery-address-1]", function() {
  alert($(this).val());
});
Palmer
  • 173
  • 9
  • Hehe, the same answer, 43 seconds faster. I spent too much time typing the explanation I guess :D Good answer. – Damb Jun 30 '14 at 16:10
  • This makes it works, thanks (even though it is located in div.data - `
    `, and thanks to @Dampe aswell and everyone else for there comments!
    – user1952067 Jun 30 '14 at 16:13
  • Ugh, it is, silly me. Always simple things I overlook! – user1952067 Jun 30 '14 at 16:16
  • 1
    So the solution would be to put the event to where you are appending, not on the document. – epascarello Jun 30 '14 at 16:18
  • Yes that's correct and I've done that now, although document still works just not preferred as you pointed out. So unless someone wants to point that out in a new answer I'll keep this checked as best. – user1952067 Jun 30 '14 at 16:22
-1

From my experience (and not just mine), it's often better to handle events of dynamic elements at global level. Meaning you will attach the event handler to document and use the selector filter to fire it only for matching elements.

eg:

$(document).on('change', 'input[name^=delivery-address-1]', function(){
  alert('hello');
});
Damb
  • 14,410
  • 6
  • 47
  • 49
  • 2
    From the [jQuery docs](http://api.jquery.com/on/#event-performance) `For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.` – epascarello Jun 30 '14 at 16:10
  • Define 'excessive'. Fair point however. You really don't want to do this for everything. – Damb Jun 30 '14 at 16:12