javascriptjquery

Delete Table Row Except in First Row


I have a form which allows the user to add a new table row via a button in the bottom row which all is working well. I now need to also add the functionality to have an additional button to allow them to delete a table row.

I gather the simplest method would be to use:

$(this).closest('tr').remove();

but I'm having trouble integrating this into the existing functionality. I also only need the "delete" button to appear on all rows except the first row (i.e. users can delete all rows except the first one). I've setup a jsfiddle here that demonstrates my current functionality:

$(window).load(function() {
  var availableTags = [
    "10 pin bowling",
    "20/20 cricket",
    "abseiling",
    "acrobatic gymnastics",
    "acrobatics",
    "acrobatics class",
    "active play",
    "activities and games",
    "aerobics",
    "AFL",
    "american football",
    "aquaerobics",
    "archery",
    "artistic gymnastics",
    "athletics",
    "aussie rules",
    "austag",
    "australian rules football",
    "backyard cricket",
    "backyard play",
    "badminton",
    "ball games",
    "ball play",
    "ballet",
    "ballet dancing",
    "ballroom dancing",
    "baseball",
    "basketball",
    "basketball practice",
    "basketball training",
    "beach",
    "beach volleyball",
    "bicycle",
    "bicycling",
    "bike ",
    "bike ride",
    "bike riding",
    "bikeriding",
    "BMX",
    "BMX bike",
    "BMX racing",
    "board surfing",
    "boarding",
    "body surfing",
    "bodysurfing",
    "boogie boarding",
    "bowling",
    "boxercise",
    "boxing",
    "boxing classes",
    "bushwalk",
    "bushwalking",
    "canoeing",
    "chasings",
    "cheerleading",
    "chopping wood",
    "circuit training",
    "climbing",
    "climbing equipment",
    "climbing trees",
    "contemporary dancing",
    "continuous cricket",
    "cricket",
    "cricket training",
    "croquet",
    "cross country running",
    "cross country skiing",
    "cross country training",
    "cycling",
    "dance",
    "dance practice",
    "dance training",
    "dancing",
    "dancing lesson",
    "discus",
    "discus throwing",
    "diving",
    "european handball",
    "fencing",
    "field hockey",
    "fishing",
    "folk dancing",
    "football",
    "football training",
    "football umpiring",
    "frisbee",
    "futsal",
    "gaelic football",
    "golf",
    "golf driving range",
    "gridiron",
    "gym",
    "gym - cardio",
    "gym - weights and cardio",
    "gym - weights/aerobics",
    "gym session",
    "gym workout",
    "gym/weights",
    "gymnastics",
    "gymnastics class",
    "handball",
    "high jump",
    "hiking",
    "hip hop dancing",
    "hip-hop",
    "hockey",
    "horseback riding",
    "horseriding",
    "hurdles",
    "ice hockey",
    "ice skating",
    "ice-skating",
    "indoor bowling",
    "indoor cricket",
    "indoor soccer",
    "inline skating",
    "irish dancing",
    "javelin",
    "jazz",
    "jet skiing",
    "jogging",
    "judo",
    "jumping on trampoline",
    "karate",
    "kayaking",
    "kickboxing",
    "kicking football",
    "kung fu",
    "lacrosse",
    "lawn bowling",
    "lifesaving",
    "light play ",
    "little athletics",
    "long jump",
    "martial arts",
    "martial arts training",
    "mini putt putt golf",
    "mixed martial arts",
    "modern dancing",
    "moguls skiing",
    "motocross",
    "motor bike riding",
    "motor cross racing",
    "motorbike",
    "motorcycling",
    "mountain biking",
    "netball",
    "netball practice",
    "netball training",
    "nippers",
    "outdoor cricket",
    "oztag",
    "physical culture",
    "pilates",
    "ping pong",
    "play computer games",
    "play wii games",
    "play with balls",
    "playground activities",
    "playing",
    "playing around",
    "playing golf",
    "playing in playground",
    "playing on equipment",
    "playing pool",
    "playing snooker",
    "playing with friends",
    "playing with toys",
    "playstation",
    "playstation games",
    "pool",
    "power walking",
    "putt putt golf",
    "racquetball",
    "rhythmic gymnastics",
    "riding bike",
    "riding rip stick",
    "riding scooter",
    "riding skateboard",
    "rip stick",
    "rip-stick",
    "ripstick",
    "rockclimbing",
    "rockclimbing gym",
    "rodeo",
    "rollerblading",
    "rollerskating",
    "rough play",
    "rowing",
    "rugby",
    "rugby football",
    "rugby league",
    "rugby league training",
    "rugby training",
    "running",
    "sailboarding",
    "sailing",
    "scooter",
    "scootering",
    "scuba diving",
    "shot put",
    "skate park",
    "skateboard",
    "ski lessons",
    "skiing",
    "skiing downhill",
    "skim boarding",
    "skipping",
    "snooker",
    "snorkelling",
    "snowboarding",
    "soccer",
    "soccer refereeing",
    "soccer training",
    "softball",
    "softball training",
    "sprinting",
    "squad swimming",
    "squash",
    "surf lifesaving",
    "surfing",
    "swim training",
    "swimming",
    "swimming laps",
    "swimming lesson",
    "swimming training",
    "T-ball",
    "table tennis",
    "tae kwon do",
    "taekwondo",
    "tai chi",
    "tap dancing",
    "ten pin bowling",
    "tennis",
    "tennis match",
    "tennis training",
    "throwing",
    "throwing javelin",
    "throwing shot put",
    "tip ",
    "tip football",
    "TKD",
    "toboganning",
    "touch football",
    "track cycling",
    "tramping",
    "trampoline",
    "trampolining",
    "treadmill",
    "treadmill running",
    "triathlon",
    "ultimate frisbee",
    "volleyball",
    "walking",
    "walking dog",
    "water polo",
    "waterskiing",
    "waterslide",
    "weightlifting",
    "weights",
    "white water rafting",
    "wii active games",
    "wii games",
    "wii sport",
    "windsurfing",
    "wrestling",
    "yoga"
  ];

  var newIDSuffix = 2;
  $('#lastYear').delegate('input[type="button"]', 'click', function() {
    var thisRow = $(this).closest('tr')[0];

    var cloned = $(thisRow).clone();
    cloned.find('input, select').each(function() {
      var id = $(this).attr('id');
      id = id.substring(0, id.length - 1) + newIDSuffix;
      $(this).attr('id', id);
    });

    cloned.insertAfter(thisRow).find('input:text').val('');
    cloned.find("[id^=lastYearSelect]")
      .autocomplete({
        source: availableTags,
        select: function(e, ui) {

          $(e.target).val(ui.item.value);
          setDropDown.call($(e.target));
        }
      }).change(setDropDown);

    $(this).remove();
    newIDSuffix++;
  });

  $(function() {
    $("#lastYearSelect1")
      .autocomplete({
        source: availableTags,
        select: function(e, ui) {

          $(e.target).val(ui.item.value);
          setDropDown.call($(e.target));
        }
      }).change(setDropDown);
  });

  if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(needle) {
      var i;
      for (i = 0; i < this.length; i++) {
        if (this[i] === needle) {
          return i;
        }
      }
      return -1;
    };
  }

  var risks = [{
    name: 'low',
    activities: ['10 pin bowling', 'active play', 'activities and games', 'aerobics', 'aquaerobics', 'archery', 'athletics', 'backyard play', 'badminton', 'ball games', 'ball play', 'ballet', 'ballet dancing', 'ballroom dancing', 'beach', 'body surfing', 'bodysurfing', 'boogie boarding', 'bowling', 'bushwalk', 'bushwalking', 'canoeing', 'circuit training', 'contemporary dancing', 'croquet', 'cross country running', 'cross country training', 'dance', 'dance practice', 'dance training', 'dancing', 'dancing lesson', 'discus', 'discus throwing', 'fishing', 'folk dancing', 'frisbee', 'golf', 'golf driving range', 'gym', 'gym - cardio', 'gym - weights and cardio', 'gym - weights/aerobics', 'gym session', 'gym workout', 'gym/weights', 'handball', 'hiking', 'hip hop dancing', 'hip-hop', 'indoor bowling', 'irish dancing', 'javelin', 'jazz', 'jogging', 'kayaking', 'kicking football', 'lawn bowling', 'lifesaving', 'light play ', 'little athletics', 'mini putt putt golf', 'modern dancing', 'nippers', 'pilates', 'ping pong', 'play computer games', 'play wii games', 'play with balls', 'playing', 'playing around', 'playing golf', 'playing pool', 'playing snooker', 'playing with friends', 'playing with toys', 'playstation', 'playstation games', 'pool', 'power walking', 'putt putt golf', 'rowing', 'running', 'scuba diving', 'shot put', 'skipping', 'snooker', 'snorkelling', 'sprinting', 'squad swimming', 'swim training', 'swimming', 'swimming laps', 'swimming lesson', 'swimming training', 'table tennis', 'tai chi', 'tap dancing', 'ten pin bowling', 'throwing', 'throwing javelin', 'throwing shot put', 'tramping', 'treadmill', 'treadmill running', 'walking', 'walking dog', 'weights', 'wii active games', 'wii games', 'wii sport', 'yoga']
  }, {
    name: 'moderate',
    activities: ['20/20 cricket', 'abseiling', 'acrobatic gymnastics', 'acrobatics', 'acrobatics class', 'artistic gymnastics', 'austag', 'backyard cricket', 'baseball', 'basketball', 'basketball practice', 'basketball training', 'beach volleyball', 'bicycle', 'bicycling', 'bike ', 'bike ride', 'bike riding', 'bikeriding', 'BMX', 'BMX bike', 'board surfing', 'boarding', 'chasings', 'cheerleading', 'chopping wood', 'climbing', 'climbing equipment', 'climbing trees', 'continuous cricket', 'cricket', 'cricket training', 'cross country skiing', 'cycling', 'diving', 'european handball', 'fencing', 'field hockey', 'football', 'football training', 'football umpiring', 'futsal', 'gymnastics', 'gymnastics class', 'high jump', 'hockey', 'horseback riding', 'horseriding', 'hurdles', 'indoor cricket', 'indoor soccer', 'jet skiing', 'jumping on trampoline', 'long jump', 'motor bike riding', 'motorbike', 'motorcycling', 'mountain biking', 'netball', 'netball practice', 'netball training', 'outdoor cricket', 'oztag', 'physical culture', 'playground activities', 'playing in playground', 'playing on equipment', 'racquetball', 'rhythmic gymnastics', 'riding bike', 'riding scooter', 'rockclimbing', 'rockclimbing gym', 'rollerblading', 'rollerskating', 'sailboarding', 'sailing', 'scooter', 'scootering', 'skim boarding', 'soccer', 'soccer refereeing', 'soccer training', 'softball', 'softball training', 'squash', 'surf lifesaving', 'surfing', 'T-ball', 'tennis', 'tennis match', 'tennis training', 'tip ', 'tip football', 'touch football', 'track cycling', 'trampoline', 'trampolining', 'triathlon', 'ultimate frisbee', 'volleyball', 'water polo', 'waterskiing', 'waterslide', 'weightlifting', 'white water rafting', 'windsurfing']
  }, {
    name: 'high',
    activities: ['AFL', 'american football', 'aussie rules', 'australian rules football', 'BMX racing', 'boxercise', 'boxing', 'boxing classes', 'gaelic football', 'gridiron', 'ice hockey', 'ice skating', 'ice-skating', 'inline skating', 'judo', 'karate', 'kickboxing', 'kung fu', 'lacrosse', 'martial arts', 'martial arts training', 'mixed martial arts', 'moguls skiing', 'motocross', 'motor cross racing', 'riding rip stick', 'riding skateboard', 'rip stick', 'ripstick', 'rip-stick', 'rodeo', 'rough play', 'rugby', 'rugby football', 'rugby league', 'rugby league training', 'rugby training', 'skate park', 'skateboard', 'ski lessons', 'skiing', 'skiing downhill', 'snowboarding', 'tae kwon do', 'taekwondo', 'TKD', 'toboganning', 'wrestling']
  }];

  function setDropDown() {

    var $this = $(this);
    var activity = $this.val();
    var i;
    for (i = 0; i < risks.length; i++) {
      if (risks[i].activities.indexOf(activity) > -1) {
        var j;
        var NextddlRisk = $(this).parents("tr").find("[id^='lastYearRisk']")[0]; //find the parent tr, then find the risk dropdown
        for (j = 0; j < NextddlRisk.options.length; j++) {
          if (NextddlRisk.options[j].innerHTML == risks[i].name) {
            NextddlRisk.selectedIndex = j;
            break;
          }
        }
        break;
      }
    }


  };

}); //]]>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<table width="100%" cellspacing="0" cellpadding="10" border="0" class="border" id="lastYear">
  <tbody>
    <tr class="d_green">
      <td colspan="6">LAST YEAR</td>
    </tr>
    <tr>
      <td width="36%">Activity</td>
      <td width="9%">Moderate risk or high risk?</td>
      <td width="13%">Number of hours per week</td>
      <td width="13%">Number of weeks per year</td>
      <td width="13%">Average number of hours per week</td>
      <td width="16%"> </td>
    </tr>
    <tr>
      <td align="center">
        <input type="text" class="input_b_r" id="lastYearSelect1" name="activity" />
      </td>
      <td class="risk">
        <select id="lastYearRisk1" name="lastYearRisk1">
          <option></option>
          <option>low</option>
          <option>moderate</option>
          <option>high</option>
        </select>
      </td>
      <td>
        <input type="text" class="input_b_r" id="lastYearHours1" name="textfield" />
      </td>
      <td>
        <input type="text" class="input_b_r" id="lastYearWeeks1" name="textfield2" />
      </td>
      <td>
        <input type="text" class="input_b1" id="lastYearAverage1" name="textfield3" />
      </td>
      <td>
        <input type="button" class="button mt5" value="Add another activity" id="button1" name="button2" />
      </td>
      <td>
        <input type="button" class="button mt5" value="Delete" id="deleteRowButton" name="deleteRowButton" />
      </td>
    </tr>
  </tbody>
</table>

So in my example when the user clicks the "Add another activity" button it should create the new table row as it currently does but also add the "delete" button which deletes that row. I've currently hard-coded the "delete" button to the first row as I'm now sure how to make it appear only for new rows created via the "add new activity" button.


Solution

  • Few changes

    In the starting markup, add the classes addbtn and delbtn also hide the delete button

    <td>
        <input type="button" class="button mt5 addbtn" value="Add another activity" id="button1" name="button2" />
    </td>
    <td>
        <input type="button" class="button mt5 delbtn" value="Delete" id="deleteRowButton" name="deleteRowButton" style="display: none"/>
    </td>
    

    Then

    $('#lastYear').on('click', '.delbtn', function () {
        $(this).closest('tr').remove()
    });
    
    var newIDSuffix = 2;
    $('#lastYear').on('click', '.addbtn', function () {
        var thisRow = $(this).closest('tr')[0];
        $(thisRow).find('.delbtn').show();
    
        var cloned = $(thisRow).clone();
        cloned.find('input, select').each(function () {
            var id = $(this).attr('id');
            id = id.substring(0, id.length - 1) + newIDSuffix;
            $(this).attr('id', id);
        });
    
        cloned.insertAfter(thisRow).find('input:text').val('');
        cloned.find('.delbtn').hide();
        cloned.find("[id^=lastYearSelect]")
        .autocomplete({
            source: availableTags,
            select: function (e, ui) {
    
                $(e.target).val(ui.item.value);
                setDropDown.call($(e.target));
            }
        }).change(setDropDown);
    
        $(this).remove();
        newIDSuffix++;
    });
    

    Demo: Fiddle