0

I have a form with multiple rows of dynamically added input fields,

I want to be able to remove the last row of these fields (provided it is not the only row)

I'm trying this as follows

The Javascript

$("#remove-item").click(function() {
    if ($('.input-row:first') !== $('.input-row:last')) {
        $('.input-row:last').remove();
    }
});

The HTML (abridged for simplplicity)

<div class="input-row">
    <input />
    <input />
    <input />
</div>
<div class="input-row">
    <input />
    <input />
    <input />
</div>

I thought this would work as in case where there is only one line of <input> fields I'm effectively selecting the same element twice by different selectors,.

In cases where the jQuery selectors match different elements, then there has to be more than one row so it should be okay to remove the last one.

Luke
  • 3,481
  • 6
  • 39
  • 63
  • You'd want to do `if ($('.input-row:first')[0] !== $('.input-row:last')[0]) {`. The problem is that every call to jQuery `$(something)` returns a **new** object. These objects **may** contain the same contents (elements), but they will never be equal, because they are references to different objects. Using `[0]`, you get a reference to the underlying DOM Element, and those references **can** be equal – Ian Oct 17 '14 at 19:47
  • Whilst I'd argue the way I was trying to solve things required knowledge of the duplicated question - the better answer to this problem is infact as suggested to look at the `length` attribute of the `div.input-row` – Luke Oct 17 '14 at 20:12

1 Answers1

4

Just check the length of those elements, if less than or equal to 1, do nothing, else remove!:

$("#remove-item").click(function() {
    if ($('.input-row').length <= 1) {
        return false;
    } else {
        $('.input-row:last').remove();
    }
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • I've tweaked you're code slightly to use a single `if() {}` rather than an `if/else` basically `if($(".input-row").length > 1 { $('.input-row:last').remove(); }` - couldn't see a need to do anything if theres only 1 – Luke Oct 17 '14 at 20:00