javascriptjqueryjquery-click-event

jQuery Click Event Reloads Page


I'm am attempting to add a new row to a table by clicking an add row button. However, clicking the add row button simply refreshes the page.

I have tried multiple ways to stop this such as preventDefualt and return false, all to no avail.

<script type="text/javascript">
  $(function() {

    $('#btn-add-item').on('click'),
      function(e) {
        e.preventDefault();
        alert("works");
        return false;
      }

  });

</script>

<button class="btn btn-primary btn-sm" id="btn-add-item"><i class="fa fa-plus"></i> Add item</button>


Solution

  • You have to close the click handler properly, check the location of end parenthesis.

    Below is the snippet with correct format:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
    
        $('#btn-add-item').on('click', // <-- removing end paranthesis after "click" event will close the function
          function(e) {
            e.preventDefault();
            alert("works");
            return false;
          }); // <-- adding end paranthesis here
    
      });
    </script>
    
    <button class="btn btn-primary btn-sm" id="btn-add-item"><i class="fa fa-plus"></i> Add item</button>