jquery - How do I add unique IDs to dynamically created input fields in Javascript? -


i using javascript create input fields dynamically limit of 10 allowed on form. need ensure these fields submitted correct place give them right id. question how do this?

$(document).ready(function () {     var max_fields = 10; //maximum input boxes allowed     var wrapper = $(".input_fields_wrap"); //fields wrapper     var add_button = $(".add_field_button"); //add button id     var x = 1; //initlal text box count      var num = new number;     var newnum = num + 1;              /*if (x = max_fields) {         alert("you can't add anymore fields.")        }     */      $(add_button).click(function (e) { //on add input button click         e.preventdefault();         if (x < max_fields) { //max input box allowed             x++; //text box increment             $(wrapper).append('<div class="clonedinput"><input id="" type="text" name="mytext[]"/><a href="#" class="remove_field">remove</a></div>'); //add input box         }     });      $(wrapper).on("click", ".remove_field", function (e) { //user click on remove text         e.preventdefault(); $(this).parent('div').remove(); x--;     }) }); 

it nice each input box have id "data_item_1" , "data_item_2", "data_item_3" etc etc. i'm not sure on how though.

you can use global variable x generate unique ids. have used x decrementing x may need use separate variable.

$(wrapper).append('<div class="clonedinput"><input id="data_item_'+itemindex+'"  type="text" name="mytext[]"/><a href="#" class="remove_field">remove</a></div>'); //add input box 

you code like

var itemindex = 2; $(add_button).click(function (e) { //on add input button click     e.preventdefault();     if (x < max_fields) { //max input box allowed         x++; //text box increment            $(wrapper).append('<div class="clonedinput"><input id="data_item_'+ itemindex++ +'"  type="text" name="mytext[]"/><a href="#" class="remove_field">remove</a></div>'); //add input box     } }); 

Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -