Reputation: 2029
I have an ADD button that adds a form field when clicked on. I want the new form field button to change when it is added to a REMOVE button. How do I change the buttons (keep in mind I'm still learning jquery). Here's my code
HTML
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }} inputFields">
<label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>
@if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
@endif
</div>
<a class="addbtn"><i class="fa fa-plus-circle fa-2x" aria-hidden="true"></i></a>
</div>
Script
$(document).ready(function(){
$(".addbtn").on('click', function(){
var ele = $(this).closest('.inputFields').clone(true);
$(this).closest('.inputFields').after(ele);
})
});
Upvotes: 1
Views: 5591
Reputation: 376
There are two options. Create two buttons and hide/show them or you can use one button and change its content to what you need. Of cours with the second option you have to check the click event if it should be a delete or an add.
I think this is what you are looking for
$(document).ready(function(){
$(".deletebtn").hide();
$(".wrapper").on('click', '.addbtn', function(){
var ele = $(this).closest('.inputFields').clone(true);
$(this).closest('.inputFields').after(ele);
var el = $(this).closest('.inputFields').next();
el.find('.addbtn').hide();
el.find('.deletebtn').show();
});
$(".wrapper").on('click', '.deletebtn', function(){
$(this).closest('.inputFields').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="form-group inputFields">
<label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="" required autofocus>
</div>
<a class="addbtn"><i class="fa fa-plus-circle fa-2x" aria-hidden="true"></i> Add</a>
<a class="deletebtn"><i class="fa fa-plus-circle fa-2x" aria-hidden="true"></i> Remove</a>
</div>
</div>
Upvotes: 3
Reputation: 1416
you can manipulate the dynamic dom object you are creating, just as you can manipulate any dom object in jquery. for example, you could do something like (just a poc, needs to keep working on this):
$(document).ready(function(){
$(".addbtn").on('click', function(){
var ele = $(this).closest('.inputFields').clone(true);
ele.find(".addbtn").replaceWith("HTML FOR REMOVE BUTTON");
$(this).closest('.inputFields').after(ele);
})
});
Upvotes: 1
Reputation: 385
Add this to your $('.addbtn').on('click'...);
...
$('.addbtn').hide();
$('.removebtn').show();
And add this to your html right below your addbtn...
<a class="removebtn">
<i class="fa fa-plus-circle fa-2x" aria-hidden="true"></i>
</a>
Upvotes: 1