Search code examples
javascriptjquerytablesorter

Prevent Javascript event when clicking on a button


I have a problem mixing associating two JavaScript functions.

I have a table sortable with tablesorter Jquery plugin. Inside my table header, I have a button "refresh" to update content table in Ajax.

The problem is that click event seems to be prevented by sort event, and I don't know how to fix that.

Edit: I would like the table no to be sorted when updating the table

Here is my table layout:

<table class="container-content" align="center" id="tableUserByAppli">
  <thead>
    <tr class="container-title">
      <th>
        <button id="btnAppli">
          <img width="16" alt="reload" src="img/refresh-icon.png">
        </button>
        Application
      </th>
      <th>
        Users
      </th>
    </tr>
  </thead>
</table>

And Js code:

$(function()
{
    $("#btnAppli").click(function()
    {
        ajaxUpdateUsersByAppli;
    });

    // dynamically set table to sortable (tablesorter)
    $("table").addClass("tablesorter");
    $("table").tablesorter({
        sortReset : true
    });

});

A JSFiddle to run my problem: http://jsfiddle.net/33rrd/


Solution

  • There are two issues that need to be addressed in the shared demo (updated demo).

    First, to ignore button clicks, wrap the header titles in a div, then target them using the selectorSort option

    HTML

    <th>
        <button id="btnAppli">
          Update
        </button>
        <div class="title">Application</div>
    </th>
    

    CSS (to reposition the button)

    th button {
        float: left;
    }
    

    Script

    $("table").tablesorter({
        sortReset : true,
        selectorSort: '.title'
    });
    

    Second, the table headers are rebuilt within the plugin, so any event binding would need to be delegated:

    $("table").on("click", "#btnAppli", function(){
        alert("test");
        //ajaxUpdateUsersByAppli;
    });