Jquery onkeypress ENTER

Asked

Viewed 825 times

1

I have a table that when you double-click on one of its fields it becomes an input and this input, when I press enter, becomes a table field again, but sometimes it doesn’t work right away, I have to click the input and then press enter. I wish I could click on the cell of the table, it turn an input, I change the information, give enter and already was.

My code JS:

function updateFabricante(op) {
    let fabricante = $(`#fabricante${op}`).text() || $(`#fabricante`).val()

    $(`#fabricante${op}`).dblclick(function(){
        $(this).html(`<input type="text" required name="fabricante" id="fabricante" value="${fabricante}">`);
        $(`#fabricante`).focus();
    });

    $(`#fabricante`).on('keypress',function(e) {
        if(e.which === 13) {
            let fabricante = $(`#fabricante`).val();
            $(`#fabricante${op}`).html(fabricante);
            return false;
        }
    });
}

(Explanation to expedite)

Where

op: Specifies which cell I am selecting, are varied, from 0 to n

manufacturer${op}: ID of the field I selected

manufacturer: input ID

  • Just in advance, it is incorrect to place the event handlers within the function (at least in this case). That’s because if you call more than once the function with the same op, will multiply the manipulators, may cause unexpected behavior, which seems to be the case.

  • How are you calling the function updateFabricante to activate the double click?

  • Yes, I noticed I was wrong now.

1 answer

0


I created a table to exemplify the Jquery code I adapted. I believe it works for your case only remaining to change the selector for your scenario.

/* Usamos $(document).ready(...) ou $(...) para garantir que todas as 
 * instruções escritas sejam aplicadas após todos os elementos 
 * do DOM (HTML) estiverem prontos para serem manipulados.
 */
$(function() {
/* Adicionando o evento de double click em todos os elementos td
 * que são filhos de qualquer elemento table.
 */
$('table td').dblclick(updateText); //Atribuindo a função updateText ao evento

/* Adicionando o evento de keypress nos elementos que tenham
 * a classe fabricante e que sejam filhos de qualquer elemento table.
 */
$('table').on('keypress', '.fabricante', function(e) {
  const key = e.which || e.keyCode;
  if (key === 13) {
    const fabricante = $(this).val();
    $(this).replaceWith('<td>' + fabricante + '</td>'); //Trocando o elemento atual (input) por um elemento td
    $('table td').dblclick(updateText); //Adicionando o evento de double click no novo elemento td criado
  }
});

function updateText() {
  $(this).off("dblclick"); //Desabilitando o evento de double click no elemento input
  const text = $(this).text();
  $(this).replaceWith('<input type="text" required name="fabricante" class="fabricante" value="' + text + '">');
  $('.fabricante').focus();
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Nome</th>
      <th>Idade</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Flávio</td>
      <td>42</td>
    </tr>
    <tr>
      <td>João</td>
      <td>15</td>
    </tr>
  </tbody>
</table>

  • Can you explain to me how this code works, please? I haven’t worked much with javascript or jquery

  • Something funny is happening to me now. I tried to use your cogido, but I don’t know why it doesn’t work I put in the "td" selector. I test with "th" and went, even with the whole table it works, but if I put "td" in this one "$('table td'). dblclick(updateText);" it does nothing. That’s why I’d like you to explain it to me.

  • I commented on my code, note that to add the double click event to the elements I used the selector to search for HTML elements (table and td). You can switch to ids or classes if it gets easier. If you still can’t understand very well, we can start a chat that helps you.

  • Okay, I got it. I don’t know exactly what was going on, but I decided to put everything in the ready document function of jquery. Thank you very much!

  • This function is used to apply the javascript code inside it right after all the DOM elements are available for use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.