Jquery replacewith - reading the id value -
using code, if change dropdown list containing opt1/opt2 alert showing id 'drop'
if clicking in 'clickme' test entry box, changes new dropdown, when change option in that, there no alert issued tell me id.
<script language="javascript"> $(document).ready(function() { $('#test').bind('click', function() { $(this).replacewith('<select id="test" name="test"><option value="volvo">volvo</option><option value="saab">saab</option><option value="mercedes">mercedes</option><option value="audi">audi</option></select>'); }); $("select").change(function(event) { alert(this.id); }); }); </script> <form> <input id='test' name='test' type='text' value='clickme.'><br> <select id='drop' name='drop'> <option value='0'></option> <option value='1'>opt1</option> <option value='2'>opt2</option> </select><br> <input type='submit' value='submit'><br> <?php if (isset($_request['test'])) echo $_request['test']; ?>
why can't see id
of new dropdown list ?
thanks
event delegation
$(document).ready(function () { $('#test').bind('click', function () { $(this).replacewith('<select id="test" name="test"><option value="volvo">volvo</option><option value="saab">saab</option><option value="mercedes">mercedes</option><option value="audi">audi</option></select>'); }); $('form').on('change', 'select[name="test"]', function (event) { alert(this.id); }); });
demo: fiddle
when use normal event registration model, register handlers directly targeted present in dom @ point of handler registration execution. elements added later dynamically not handlers.
the solution use event delegation, in model handler registered ancestor element present when page loaded selector filter out source element. makes use of event propagation - events happening in element propagated ancestor elements(there few exceptions focus event). event happening in element gets propagated ancestor element in 1 of them handler registered events source element(event.target) , ancestors matched against selector passed second parameter, if satisfied handler executed.
Comments
Post a Comment