javascriptjqueryunbind

js .off() is not working on <tr> elements


I have a table with <tr> having ew <input> elements with onchange event declared at design time but filled dynamically from database. The HTML of the <td > looks like this:-

<td scope="col" style="width: 60px; font-weight: normal;">
  <input type="text" id="hall_name" name="hall_name" class="form-control" onchange="rowEdited($(this).parent())" value=<%=hallName %> ></input>
</td>
<td scope="col" style="width: 50px; font-weight: normal; text-align: center">
  <input type="text" style="text-align: center" id="hall_capacity" name="hall_capacity" onchange="rowEdited($(this).parent())" class="form-control" value=<%=hallCapacity %>></input>
</td>
<td scope="col" style="width: 75px; font-weight: normal; text-align: center">
  <input type="text" id="hall_location" name="hall_location" onchange="rowEdited($(this).parent())" class="form-control" value=<%=hallLocation%>></input>
</td>

After cloning the last <tr>, I am attempting to remove the onchange events from all inputs in the last <tr> but it is not working.

The js code to clone the last <tr> looks like this:-

var row = $('#hallTable tr:last');
var new_row =  $(row).clone(false,false).off();

The Javascript codes I attempted until now are like this

$('#hallTable tr:last').find("*").off();

and

$('#hallTable tr:last').find(':input').each(function(){
    $(this).unbind('onchange', rowEdited);
})

$('#hallTable tr:last').find('input:checkbox').each(function(){
    $(this).unbind('onchange', rowEdited);

and

    $('#hallTable tr:last').find('input').onchange = null;

and

$('#hallTable tr:last').find('input').unbind('onchange', 'rowEdited');

But none are working. Please advise.


Solution

  • The jQuery .off() or unbind functions remove only event listeners that have been added using jQuery. They won't remove inline event listners (like onchange="rowEdited($(this).parent())").

    To remove the inline event listner onchange for all ements that match $('#hallTable tr:last').find('input') you would need to write:

    $('#hallTable tr:last').find('input').each(function() {
      this.onchange = null;
    })
    

    In general you should not use inline events at all. Either use addEventListener or if you want to use jQuery then use .on().