I have one problem with my function in jQuery. First I will explain what I am trying to do.
I have two elements inside a div, the p element and input element. The element p is visible, and the input element stay hidden. When the user clicks in the p element, the input element will appear (show and focus) and the p element will disappear (hide). When the input field appears, if the user types something and presses enter, a new li element will be added.
This is my current code:
function createFolder() {
// Should be a clickable element
$('#create p').click(function() {
// Hide the p element
$(this).hide();
// Show and focus the createFolder (input field)
$('#createFolder').show().focus();
// If press a key inside input field
$('#createFolder').keypress(function(event) {
// If this key is "enter"
if (event.keyCode == 13) {
// Add a new li element inside menu
$('#menu').append('<li class="expandable"><a href="#">' + $('#createFolder').val() + '</a></li>');
}
});
// Focus out the input field
$('#createFolder').focusout(function() {
// Hide the input field element
$(this).hide();
});
});
}
But I have a problem, when I click in p element or focus out (3 clicks for example), when I type something and press enter, three li elements are added to my menu. It's like a loop, it counts my clicks and focus out and when I type something, it adds that number of elements. Someone can help me with this? And if is possible, teach me why this happens?