1

Porque eu não consigo digitar texto no input ".tarefa-edit" que foi criado com o jQuery?

$(function(){
    function onTarefaDeleteClick(){
        $(this).parent('.tarefa-item').hide('slow', function(){
            $(this).remove();
        });
    }
    $('.tarefa-delete').click(onTarefaDeleteClick);
});
$(function(){
    function onTarefaItemClick(){
        var text = $(this).children('.tarefa-texto').text();
        var html = '<input type="text" ' + 'class="tarefa-edit" value="' + text + '">';
        $(this).html(html);
        $('.tarefa-edit').keydown(onTarefaEditKeydown);
    }
    $('.tarefa-item').click(onTarefaItemClick); //
});
function onTarefaEditKeydown(event){
    if(event.which === 13){
        savePendingEdition($(this));
    }
}
function savePendingEdition(tarefa){
    console.log('...');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="todo">
    <h2>TODO List</h2>
    <input type="text" id="tarefa">
    <div id="tarefa-lista">
        <div class="tarefa-item">
            <div class="tarefa-texto">Comprar pão</div>
            <div class="tarefa-delete"></div>
            <div class="clear"></div>
        </div>
    </div>
</div>

2
  • Para que serve a função onTarefaEditKeydown? Pq se vc está no input de cima e dá um tab para o input criado ele recebe texto normalmente, mas, se clicar no input ele não recebe mais o foco.
    – LeAndrade
    12/07/2018 às 15:29
  • .keydown não costuma funcionar com elementos criados dinamicamente, sugiro trocar por $(document).on('keydown', ".tarefa-edit",onTarefaEditKeydown) . Teste e informe se deu certo, não consegui testar porque não tem um exemplo testável na sua pergunta 12/07/2018 às 16:25

1 Resposta 1

1

O que está ocorrendo que você associou a função onTarefaItemClick ao evento "click" da tag <div class="tarefa-item">, então quanto você clicar na caixa <input type="text" class="tarefa-edit" value=""> que está dentro da tag <div class="tarefa-item"> o evento "onTarefaItemClick" e chamado novamente recriando a caixa de texto, você desabilitar evento onclick da tag <div class="tarefa-item"> após criação da caixa de texto o problema não vai ocorre:

$(function(){
    function onTarefaItemClick(){
        $('.tarefa-item').unbind();
        var text = $(this).children('.tarefa-texto').text();
        var html = '<input type="text" ' + 'class="tarefa-edit" value="' + text + '">';
        $(this).html(html);
        $('.tarefa-edit').keydown(onTarefaEditKeydown);
    }
    $('.tarefa-item').click(onTarefaItemClick); //
});

Você deve fazer log-in para responder a esta pergunta.