reyjoel reyjoel - 4 months ago 9
jQuery Question

Append then delete but dont delete the last input text or row

i have this simple append and then remove i can remove it all but the problem is how can i disable remove if their is only one remaining input text?

my remove jQuery Script

jQuery(document).on("click",".remove",function(){
var doc = jQuery(this);
var remove = doc.closest(".list");
var del = jQuery(".remove").length;
if(del < 1){
remove.remove();
}
});


if you need other details just in case here is the HTML

<body>
<div id="wrap">
<ul>
<li class="list"><input type="text"> <a href="#" class="remove">x</a></li>
</ul>
</div>
<a href="#" class="add">Add</a> <a href="#" class="save">Save</a>
</body>


and ADD jQuery Script

jQuery(document).on("click",".add",function(){
var counter = jQuery(".list").length;
var add = "<li class='list'><input type='text'> <a href='#' class='remove'>x</a></li>";
if(counter < 10){
jQuery("ul").append(add);
}else{
alert("Maximum is 10.");
}
});

Answer

Just change the less than to greater than in your remove handler.

jQuery(document).on("click",".remove",function(){
    var doc = jQuery(this);
    var remove = doc.closest(".list");
    var del = jQuery(".remove").length;
    if(del > 1){
        remove.remove();
    }         
});
Comments