First Question on the overflow so forgive me in advance for any issues or if I missed a previous answer. I am a little new to jQuery so there may be issues with the way that I am coding. I am trying to build a dynamic form that will allow me to add text input fields as needed by a user. It works very well until I try to use a cloned button to add more fields.
I am using jquery-ui 1.11.2 and jquery 1.11.2
HTML Code:
<style>.hiddenForm{display:none};</style>
<form>
<input id="numentries" class="numspinner" />
<div class="repeatedForm hiddenForm">
<input type="button" class="numbutton" value="Add Fields" />
<div class="repeatedInnerForm hiddenForm">
<input type="text" placeholder="Gimme information" />
<input type="text" placeholder="Gimme more information" />
</div>
</div>
</form>
Javascript
$(".numspinner").spinner({min:1});
$(".numspinner").on("spin",function(event, ui){
var oldvalue = $(this).val();
var newvalue = ui.value;
var diff = newvalue - oldvalue;
if(newvalue >= 1){
if(diff == 1){
var newForm = $(".repeatedForm").clone(true);
newForm.removeClass("repeatedForm");
newForm.removeClass("hiddenForm");
newForm.attr("id","innerForm"+newvalue);
newForm.appendTo("form");
}else if(diff == -1){
$("#innerForm"+oldvalue).remove();
}
}
});
$(".numbutton").button();
$(".numbutton").click(function(event){
var buttonclicked = $(this);
var newForm = $(".repeatedInnerForm").clone();
newForm.removeClass("repeatedInnerForm");
newForm.removeClass("hiddenForm");
newForm.insertAfter(buttonclicked);
});
JSFiddle
I would like it to only display one set of text fields for each button press and associate the textfields with the button being pressed. I think it has to do with the initial clone of the button. Any input or constructive criticism on code style is appreciated.
I'm not 100% sure this does what you hope, but I changed your code to add the number of fields based on the inputs value:
For this HTML
See it in action here