3
I intend to create a seemingly very 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>
<div class="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 bhuões to function in their respective functions: remove to div#coordenates
where they are present and add a new div#coordenates
after which you are present. However, as you may pecerber in my example, I did not succeed.
The reason for my failure is the fact that the elements are created dynamically, despite having managed a way to assign events to them through of that question, I still can’t properly capture the index
of these elements using their classes, when they are clicked. The index
is necessary to know in which div
are, and so delete it or add a following.
If there is another way to accomplish my goal (remove/add), I am also open to new possibilities. I appreciate any help.
That’s exactly what I was looking for. Thank you.
– Samir Braga
@Nothing Samirbraga, I’m glad I helped.
– Sergio