Can't unbind keypress event after the key is pressed once
I've created an input field that submits a simple field when the enter key (13) is pressed. The code works if you pressed the key the first time but then it never works again until i refresh the page. I'm trying to unbind the event but nothing happens.
开发者_开发问答$(function () {
$('#new_list').bind('keypress', function (e) {
if(e.which === 13) {
console.log('enter pressed');
var nl_val = {};
nl_val['list_name'] = $('#new_list').val();
$.post('/lists/js_new_list',nl_val,function(str) {
if(str == 'error') {
$('#info').css({'color':'red'})
.fadeIn(1000)
.text('There was an error.')
.fadeOut(1000);
} else {
$('#new_list').hide().val('');
$('#info').css({'color':'#00620C'})
.fadeIn(1000)
.text('List created.')
.fadeOut(1000);
js_refresh_lists();
}
});
$('#new_list').unbind("keypress");
} // UPDATE: this is the if(e.which === 13) end
});
});
function js_refresh_lists() {
var id = list_id();
console.log('refreshing list');
$('#lists').load('/lists/js_refresh_lists');
}
UPDATE: I want the user to be able to add another list (my case) without the need to refresh the page to get the keypress event working again. At the moment as mentioned at the top of this post, it only works the first time a new list is added, after that the enter key does nothing.
Can anyone figure out why the key is unbinding?
Cheers
I think your problem is that after the first successful keypress you refresh your form with js_refresh_lists() which replaces your #new_list field with a new one, which does not have the keypress bind on it.
In the above case you have 2 options:
- put your keypress init in a separate function, and execute it on every list refresh
- use live binding .live("keypress", fn) on load
精彩评论