Phantom
Phantom

Reputation: 688

jQuery Problems with removing event handler with .off()

I have tried to remove an event handler with .off(), but it does not work.

I want to remove all event handlers from one certain input:

<input type="file" id="file_upload" name="file_upload" size="50" />

Here is what I have tried:

$('#form').on('keyup change', ':input', function() {
    registerChange();
});
$('#form input[name=file_upload]').off();
$('#file_upload').off();

Upvotes: 1

Views: 173

Answers (3)

robbmj
robbmj

Reputation: 16496

You can use a not selector for the file upload button

$('#form').on('keyup change', 'input:not([name=file_upload])',  function() {
  registerChange($(this).val());
});

function registerChange(value) {
  // notice that typing into the upload textbox does not log anything to the console
  console.log(value);
}

$('#form').on('click', 'input[name=file_upload]', function () {
  alert('In Click Event Handler, Now Removing Myself');
  // here is how you can remove an event handler
  $('#form').off('click', 'input[name=file_upload]');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form">
  <input type="text" />
  <input type="text" />
  <!-- just changeing this to a textbox for demo -->
  <input type="text" id="file_upload" name="file_upload" size="50" value="Choose file" />
</form>

Open the console window (CTRL+SHIFT+J in chrome) and type into all of the text boxes. Notice how only the first 2 text boxes write to the console. Also note that the last text box defines an on click handler then removes it, this is why the alert only shows up once.

Upvotes: 1

Vitaliy Terziev
Vitaliy Terziev

Reputation: 6671

Try this:

$('#file_upload').off('keyup change', ':input', function()
{
    registerChange();
});

Upvotes: 0

dfsq
dfsq

Reputation: 193261

You are binding event to form element. So in order to remove it you again need to use form tag:

// bind delegated events to form element
$('#form').on('keyup change', ':input', function () {
    registerChange();
});

// remove events later
$('#form').off();

You are probably confused with event delegation: this usage of on method attaches events to the form element, where they are captured after bubbling from children :input.

Upvotes: 1

Related Questions