I have a page that has multiple forms that i need to use the same JavaScript code on. The JavaScript code adds more input fields to the form. The script works fine but adds input fields to all forms. I need it to only add fields to the current form being filled out. So far I haven't had any luck.
Here is what one of the forms looks like:
<form>
<div class="price-group">
<div class="price-fields">
<label>Multiple <a class="add-field" href="#"> Add Field</a></label>
<br><input maxlength="7" type="text" name="prices[]" />
</div><!--end form-group price-fields-->
</div><!--end price-group-->
</form>
Here is my JavaScript:
$(document).ready(function($){
$('.price-group .add-field').click(function(e){
e.preventDefault();
var n = $('.price-fields').length;
$('.price-group').append('<div class=" price-fields"><input maxlength="7" type="text" name="prices[]" /><a class="remove-field pull-right" href="#">Remove</a></div><!--end form-group-->');
});
$('.price-group').on('click', '.remove-field', function(){
$(this).parent().fadeOut("slow", function() {
$(this).remove();
});
return false;
});
});
I set up jsfiddle: JsFiddle Link
You can use jQuery closest
to find the closest .price-fields
to the clicked <a>
tag:
$(document).ready(function($){
$('.price-group .add-field').click(function(e){
e.preventDefault();
var n = $('.price-fields').length;
$(this).closest('.price-group').append('<div class=" price-fields"><input maxlength="7" type="text" name="prices[]" /><a class="remove-field pull-right" href="#">Remove</a></div><!--end form-group-->');
});
$('.price-group').on('click', '.remove-field', function(){
$(this).parent().fadeOut("slow", function() {
$(this).remove();
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="price-group">
<div class="price-fields">
<label>Multiple <a class="add-field" href="#"> Add Field</a></label>
<br><input maxlength="7" type="text" name="prices[]" />
</div><!--end form-group price-fields-->
</div><!--end price-group-->
</form>
<form>
<div class="price-group">
<div class="price-fields">
<label>Multiple <a class="add-field" href="#"> Add Field</a></label>
<br><input maxlength="7" type="text" name="prices[]" />
</div><!--end form-group price-fields-->
</div><!--end price-group-->
</form>
<form>
<div class="price-group">
<div class="price-fields">
<label>Multiple <a class="add-field" href="#"> Add Field</a></label>
<br><input maxlength="7" type="text" name="prices[]" />
</div><!--end form-group price-fields-->
</div><!--end price-group-->
</form>