I intend to create a seemingly simple function. My code is this:
var coordenates = $(".coordenates");
var add = $('.add');
var remove = $('.remove');
var newCoordenate = '<div class="coordenates"><input type="text" />, <input type="text" /> <input type="button" class="addRemove remove" value="-" /><input type="button" class="addRemove add" value="+" /></div>';
function addCoordenate() {
var i = add.get().indexOf(this);
coordenates.eq(i).after(newCoordenate)
}
function removeCoordenate() {
var i = remove.get().indexOf(this);
coordenates.eq(i).remove();
}
$('.coordenateBox').on('click', '.coordenates .add', function() {
addCoordenate();
});
$('.coordenateBox').on('click', '.coordenates .remove', function() {
removeCoordenate();
});
.coordenates {
height: 30px;
box-sizing: border-box;
margin: 5px 0;
}
.addRemove {
width: 30px;
height: 30px;
background: #00ae84;
color: #fff;
font-size: 120%;
border: none;
text-align: center;
line-height: 25px;
opacity: 0.6;
cursor: pointer;
}
.addRemove:hover {
opacity: 0.9;
}
.addRemove:nth-child(odd) {
background: #f00;
}
.coordenates input[type="text"] {
height: 30px;
}
.coordenates input {
display: inline-block;
box-sizing: border-box;
vertical-align: top;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divclass="coordenateBox">
<div class="coordenates">
<input type="text" />, <input type="text" />
<input type="button" class="addRemove remove" value="-" onclick="removeCoordenate()"/><input type="button" class="addRemove add" value="+" onclick="addCoordenate()" />
</div>
</div>
What I want is for the buttons to work in their respective roles: remove the div#coordenates
they are present in and add a new div#coordenates
after they are gifts. However, as you can pecerber in my example, I did not succeed.
The reason for my failure is that elements are dynamically created, even though they have been able to assign events to them by of this question , I still can not correctly capture index
of these elements using their classes when they are clicked. The index
is required to know what div
are, and thus deleting it or adding a next one.
If there is another way to accomplish my goal (remove / add), I am also open to new possibilities. Thanks for any help.