javascript - Jquery Children's child elemnt -
$(parentquestion.children('.choice_class:last')); <div class='parentquestion'> ..... <div class="choice_class"> <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12"><span class="choice-no">option 1</span><span class="required">*</span> </label> <div class="col-md-6 col-sm-6 col-xs-12"> <input type="text" required="required" class="form-control col-md-7 col-xs-12"> </div> <a href="javascript: void(0);" onclick="addoption(this)" class="btn btn-danger"><span class="glyphicon glyphicon-plus"></span>add choice</a> </div> </div>
inside addoption function, using variable, found parent object , added option below last .choice_class.
i need change option 1 option 2 when second option added.
the complete function is
function addoption(that) { $(that).parent().parent().after($('.choice_class_sample .choice_class').clone()); var parentquestion = $(that).parent().parent().parent(); var lastchoice = parentquestion.children('.choice_class:last'); $(parentquestion.children('.choice_class:last-child .choice-no')).html(parentquestion.children('.choice_class').length); $(that).remove(); }
but not able select further more after selecting children.
i modify code "make work", way you're going little bit unorthodox – namely, using clone
copy existing element before duplicating it.
if you're going representing javascript data structure (like array) in dom, , wanting keep them in sync, it'd better use templating system. since you're using jquery, jquery template plugin seems decent. skimming readme, make stuff simple this:
<script type="text/html" id="template"> <div> <div> <label> <span>option <span data-content="id"></span></span> <span class="required">*</span> </label> <div> <input type="text" required="required"> </div> <a href="#" class="add-choice-button"><span class="glyphicon glyphicon-plus"></span> add choice</a> </div> </div> </script>
then, in javascript, you'd have like:
var options = [ { id: 1 } ] parentquestion.loadtemplate("#template", questions) $('.add-choice-button').on('click', function () { options.push({ id: options.length + 1 }) parentquestion.loadtemplate('#template', options) })
much, cleaner. , best of all, avoids having ugly, imperative dom manipulation in js.
Comments
Post a Comment