lundi 1 décembre 2014

Dynamically Add Form Fields and Update Field Value


I have a form that you can add fields: http://ift.tt/1vdfj9s



$(document).ready(function() {
var max_fields = 32; //maximum input boxes allowed
var wrapper = $(".cameras"); //Fields wrapper
var add_button = $(".add-camera"); //Add button ID

var x = 1; //initlal text box count
$(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="form-group"><input type="text" name="camera '+ x +'" value="Camera '+ x +'" placeholder="Camera '+ x +'" class="form-control cameras" readonly /> <a href="#" class="remove-camera">Remove</a></div>'); //add input box
}
});

$(wrapper).on("click",".remove-camera", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})


});



<div class="cameras">
<div class="camera-field"><button class="add-camera btn btn-primary">+ Add Camera</button></div>
<div style="clear:both;"></div>

<div class="form-group"><input type="text" name="camera" value="" placeholder="Camera 1" class="form-control cameras" readonly /></div>

</div>


Everything works fine adding fields, but where I'm hung up is when you remove one of the fields then numerical order gets off.. how do I make it update the remaining fields to stay in proper numerical order each time you add or remove a field:


Camera 1

Camera 2

Camera 3

etc...


Thanks ahead of time!





Aucun commentaire:

Enregistrer un commentaire