jQuery - How to set a select which doesn't exist yet -
i have next html:
... <div> <select id="select_1" name="select_1"> <option value="1" selected="selected">option 1</option> <option value="2">option 2</option> ... </select> <a id="add_1">add new</a> </div> <div> <select id="select_2" name="select_2"> <option value="1" selected="selected">option 1</option> <option value="2">option 2</option> ... </select> <a id="add_2">add new</a> </div> ... when click on "add new" link new div select created. need set new select, don't know how beacuse doesn't exist yet. i'm trying this:
$(document).ready(function() { $('[id^=add_]').on('click', function() { var new_select = $(this).parent().next().find('[id^=select_]'); // doesn't work. way it? ... }); }); }); thanks.
use delegated event handler, attached non-changing ancestor element, add together buttons. use classes add together button (you not need ids there) use closest in preference parent allow future dom changes. calculate new name/id based on number of existing items use template div, stored in dummy script block convenience.
jsfiddle: http://jsfiddle.net/trueblueaussie/455ahpyw/4/
$(document).ready(function() { $(document).on('click', '.add', function(e) { e.preventdefault(); var $div = $(this).closest('div'); // append template , replace id existing number of these +1 var id = "select_" + ($("[id^=select_]").length + 1); var $template = $($('#template').html()); $template.find('select').attr('id', id).attr('name', id); $div.after($template); }); }); explanation of delegated event handlers:
they work listening specified event bubble non-changing ancestor, then apply jquery selector, then apply function matching elements that caused event. means work on elements exist @ event time , not @ registration time (which when "normal" handler connects).
jquery
No comments:
Post a Comment