javascript - how to get separate id for same input type while creating dynamic input filed? -
js file
in below javascript file how can create different id input types whenever new input type being created.
$(document).ready(function(){ $(".template_charge:first").hide(); //hide template var charge_count =0; // total charge types. var charge_id_no =0; // assign id , name charge component /* add new item based on hidden template */ $(".add_charge").click(function() { charge_id_no ++; charge_count ++; $('#charge_count').val(charge_count); var newitem = $(".template_charge:first").clone(); newitem.find("input").attr("id", "chargetype_" + charge_id_no); //rewrite id's avoid duplicates newitem.find("input").attr("name", "chargetype_" +charge_id_no); newitem.find("input").attr("id", "charge_" +charge_id_no); //rewrite id's avoid duplicates newitem.find("input").attr("name", "charge_" +charge_id_no); newitem.show(); //show clone of template $(".template_charge:last").after(newitem); bindremove(); }); /* bind remove function last added button*/ function bindremove() { $(".remove_charge:last").click(function(e) { if ($(".remove_charge").length > 1) $(this).parents(".template_charge").remove(); charge_count--; $('#charge_count').val(charge_count); }); } /* execute bind-function @ startup */ bindremove(); });
html file
html files if input type being created whenever add button clicked.
<input type="hidden" id="charge_count" name="charge_count" value="0"/> <div class="form-group col-md-12" id="other_charge"> <div class="form-group col-md-12 col-sm-12"> <label for="other_charges" class="control-label col-md-2">other charges</label> <button id="b2" class="btn btn-info add_charge col-md-10 col-sm-12" type="button">add</button> <div class="template_charge col-md-offset-2"> <div class="controls" id="profs"> <div id="field_charge" class="form-group input-append col-md-12"> <input autocomplete="off" class="input form-control col-md-5" id="field3" name="charge1" type="text" placeholder="charge type" /> <input autocomplete="off" class="input2 form-control col-md-5" id="field4" name="charge2" type="text" placeholder="charge" min="0" max="100" /> <button class="remove_charge btn btn-danger form-control col-md-2" type="button">x</button> </div> </div> </div> </div> </div>
... bit of guess, without being able see template, perhaps template root input
, calling find
returns 0 length set, not work. try this...
newitem.find("input").attr(/* etc... */);
... should read ...
newitem.attr(/* etc... */);
Comments
Post a Comment