Home > database >  Jquery .append() appends on every event
Jquery .append() appends on every event

Time:06-05

I have very minimal javascript and jquery knowledge, so the problem is, when click with mouse "li" tab and press ENTER jquery attach .append() on every mouse click event.

$(document).on("click", function(event){
        let $ul_elem = $(event.target).parent().parent();
        const $li = '<li><input type="text" name="geras"></li>'
        
        if($(event.target).parent().prop("localName")=="li"){ 
            console.log($(this.event))
            $(window).on("keydown", function(event){
                if(event.keyCode == 13) {
                    event.preventDefault();
                    $($ul_elem).append($li);
                    $($ul_elem).children().last().children().focus();   
                    return false
                }
            })
        }
        else{
            $(window).unbind("keydown");
        }      
    })

in result if i click like 5 times with my mouse on the same li tab, it will create 5 new const $li elements and i dont want that.

CodePudding user response:

You should avoid binding event handlers in context of another event handler. Your code currently rebinds the keydown handler on each click (when the if statements succeeds.) This is why the code appends several elements on each Enter. I guess you want to append li elements to ul elements conditionally. If yes this is one way of doing it:

$(document).on("click", "ul", function() {
     $(this).toggleClass('active');
});

$(window).on("keydown", 'ul.active', function(event) {
     if (event.keyCode == 13) {
         const $ul_elem = $(this);
         const li = '<li><input type="text" name="geras"></li>'
         event.preventDefault();
         $ul_elem.append(li);
         $ul_elem.children().last().children().focus();   
         return false
     }
})

This makes the keydown handler work conditionally by using event delegation. In case you want to listen to the keydown event of input elements you can just code $(document).on("keydown", 'input[type=text]', function(event) { ... and there is no need to use click handler. I'm still not sure what you are trying to achieve though.

what I want to do is after i put text in my default li > input field and press ENTER i want to create new li in ul

This should do it:

$(document).on("keyup", 'li input[type=text]', function(event) {
    if (event.keyCode == 13) {
        const $ul_elem = $(this).closest('ul');
        const li = '<li><input type="text" name="geras"></li>'
        event.preventDefault();
        $ul_elem.append(li);
        $ul_elem.children().last().children().focus();   
    }
})
  • Related