I've got the following code:
$(function(){
var $name = $('#name'),
$save = $('#save');
function alertName(){
var name = $name.val();
return alert(name);
};
function addSaveEvent(elem){
return elem.bind('click',function(e){e.preventDefault();alertName();});
};
$name.bind('keyup',function(){addSaveEvent($save);});
$(window).load(function(){
$save.bind('click',function(e){e.preventDefault();});
});
});
What is the function? When the page loads, the button is 'not' clickabled eg. the button does nothing. When the input field "name" changes, the button 'becomes' clickable and will call the function alertName().
What is the problem? Everytime something is typed -> everytime a new "keyup", so if you type 'Hello' in the input field 'name' and you click on the button, the function alertName() is fired 5 times (H E L L O). If you delete this and click the button again, it's fired 10 times (H E L L O [backspace]x5).
I think that every time the 'keyup' event is fired, the function addSaveEvent is bind on the save button. But I don't want this, i just want it to be bound only once, not 5, 10, ... times.
How can I check if an event is already bound to an element? If not => bind, if so => no extra bind (but also NO unbind)?
Thanks in advance!
PS: I have checked the following questions: - How to check if click event is already bound - JQuery - jQuery check if event exists on element
Those are about the 'click' event, and not about the 'keyup' event, and I don't understand them very well. :/