0

new member but I've been reading and learning here for a bit. I hope I"ve formatted this question correctly but here goes. Here's the basics of my problem. I'm using JQuery replaceWith to swap a dropdown select with an input box and vice-versa. It seems that I'm affecting the ability of JQuery to set focus() on the swapped out id. Here's the code (no closing tags).

For the form Select A Sign lawn signs banners carved signs sandblasted signs Quantity:

the JQuery that swaps the drop down select with the input box which happens on a change of the product id shown above newField either contains on or the other of the following:

            newField = "<select id='quantity' name='quantity'><option selected value='10'>10</option><option value='20'>20</option><option value='30'>30</option><option value='40'>40</option>option value='50'>50</option><option value='60'>60</option><option value='70'>70</option><option value='80'>80</option><option value='90'>90</option><option value='100'>100</option></select>";

            newField = "<input id='quantity' name='quantity' maxlength='2' size='2' \>"

and the JQuery replaceWith() which will swap out one of the two fields above depending upon another selection drop down box.

        $('#quantity').replaceWith($(newField)).attr("id", "quantity");

This all works just fine and the swaps work great except that when I do the following (my test code), nothing happens. No alert is triggered when I focus into the input box.

$('#quantity').focus(function(){
    alert ("focused");
});

Am I losing some sort of context on the id with the swap using replaceWith() since the id is the same regardless of whether I swap a select drop down with an input box.

Thanks

  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Barmar Mar 06 '14 at 17:52

2 Answers2

0

You should use .on() for binding events to dynamically created elements. Try:

$(document).on('focus','#quantity',function(){
    alert ("focused");
});
Kiran
  • 20,167
  • 11
  • 67
  • 99
  • This worked perfectly. Thank you very much. When creating the object I didn't see it as dynamic so no events were attached. Attaching the events did the trick. I've been learning JQuery for a short time so the nuances of the implementation got by me. – user3388569 Mar 07 '14 at 23:29
0

you should use deligates for dynamically created objects

$(document).on("focus","#quantity",function(){
alert ("focused");
});
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
  • This won't work if executed inside of the ``, and you have a syntax error – Ian Mar 06 '14 at 17:26
  • This will work. I did use .on() to create the event binding and it worked perfectly. I wonder if there is a benefit to delegating that the .on() does not provide? Thanks Anoop. – user3388569 Mar 07 '14 at 23:31