I have a todo list that I made with the help of Pranav Rustagi and Twisty. I still have a problem for which I can’t find a solution.
Between each text added, I want to add a separator (pipe). My problem is that when I delete the first element, the next element, which becomes the first one, has an unwanted pipe.
So how can I add a separator only if there is more than one element, and only if it’s not the first element ?
To reproduce the scenario: add a, b, c, and then delete a. You’ll see the pipe before the b still there. Is it better to imagine a pipe only if there is an element after?
One main issue here is the empty() inside the remove function. It doesn’t delete the span.output from the DOM so I cannot use first() or do something in css like :
.output:not(:first-of-type):before {
content:'|';
padding:0 5px;
}
I can’t use remove() instead of empty() either because I won’t be able to add a line again if I delete them all.
Any help would be appreciated.
$(function() {
$(".container").on('input', 'input[type=text]', function(event) {
var i = $(this).closest(".flex-row").index();
var v = (i == 0) ? $(this).val() : "|" + $(this).val();
$("#custom_wrapper .output").eq(i).html(v);
});
$('.add').click(function() {
var count = $("input").length;
count++;
var row = $("<div>", {
class: "flex-row"
}).insertBefore(this);
$("<label>").appendTo(row);
$("<input>", {
type: "text",
class: "input",
id: "custom-text-" + count,
placeholder: "custom text " + count,
tabindex: count
}).appendTo($("label", row));
$("<button>", {
class: "remove"
}).html("-").appendTo(row);
$("<span>", {
class: "output",
dataid: "custom-text-" + count
}).insertAfter($("#custom_wrapper .output:last"));
});
$('body').on('click', '.remove', function() {
$(this).parent('.flex-row').remove();
var j = $(this).parent().find('.input').attr("id");
$('#custom_wrapper .output[dataid="' + j + '"').empty();
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div class="container">
<div class="wrapper">
<article>
<section>
<div class="flex-row">
<label
><input
class="input"
type="text"
name=""
id="custom-text-1"
placeholder="custom text"
tabindex="1" /></label
><button class="remove">-</button>
</div>
<div class="flex-row">
<label
><input
class="input"
type="text"
name=""
id="custom-text-2"
placeholder="custom text 2"
tabindex="2" /></label
><button class="remove">-</button>
</div>
<button class="add">+</button>
<div class="flex-row">
<div class="token">
{{customText[<span id="custom_wrapper"><span class="output" dataid="custom-text-1"></span><span class="output" dataid="custom-text-2"></span></span>]}}
</div>
</div>
</section>
</article>
</div>
</div>