Yevgeniy Bagackiy Yevgeniy Bagackiy - 3 months ago 5
HTML Question

Javascript code cant be run

I'm stuck with this javascript code. I want to add a new row to the table and then be able to remove it. I just can't find my mistake.

Here is my code:

<!DOCTYPE html>
<html>
<head>
<script>
$('.Add').click(function()
{
var row = $(this).closest('tr').clone();
row.find('input').val('');
$(this).closest('tr').after(row);
$('input[type="button"]', row).removeClass('Add').addClass('RemoveRow').val('Remove item');
});

$('table').on('click', '.RemoveRow', function()
{
$(this).closest('tr').remove();
});
</script>
</head>

<body>
<table>
<tr>
<td>Process:</td>
<td>People required:</td>
<td>Add/Remove Item</td>
</tr>
<tr>
<td>
<select name="process">
<option value="1">BLD</option>
<option value="2">KEY</option>
<option value="3">ART</option>
<option value="4">BG</option>
</select>
</td>
<td><input type='text' ></td>
<td><input type='button' class='Add' value='Add new item'></td>
</tr>
</table>
</body>
</html>

Answer

You are using jQuery, but missing the jQuery reference.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Add your jQuery code on DOM ready function.

Working code:

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script>
    $(function() {
      $('.Add').click(function() {
        var row = $(this).closest('tr').clone();
        row.find('input').val('');
        $(this).closest('tr').after(row);
        $('input[type="button"]', row).removeClass('Add').addClass('RemoveRow').val('Remove item');
      });

      $('table').on('click', '.RemoveRow', function() {
        $(this).closest('tr').remove();
      });
    });
  </script>
</head>

<body>
  <table>
    <tr>
      <td>Process:</td>
      <td>People required:</td>
      <td>Add/Remove Item</td>
    </tr>
    <tr>
      <td>
        <select name="process">
          <option value="1">BLD</option>
          <option value="2">KEY</option>
          <option value="3">ART</option>
          <option value="4">BG</option>
        </select>
      </td>
      <td>
        <input type='text'>
      </td>
      <td>
        <input type='button' class='Add' value='Add new item'>
      </td>
    </tr>
  </table>
</body>

</html>

Comments