Click on information, display a text field, change information and save automatically

Asked

Viewed 42 times

-1

How can I make the user click on information coming from BD, this information becomes a text field, the person changes the information and when click outside the field, save automatically? As in Phpmyadmin.

  • You generate the input dynamically in the DOM, with the bank’s current value; when the field receives the event blur you make a request by updating in the bank. Want to try?

  • Hi Anderson. Could you give me an example? I confess that I don’t have much experience with Jquery.

  • A contenteditable wouldn’t solve your case?

  • Right Leandrade, but how would I make it so that, through Jquery, I could change the content of BD (Mysql)? The PHP that makes the editing is all ok, I would just like to click on the text, appear the field as you passed, but when clicking outside the field, update automatically in the BD.

1 answer

1


Below is a basic example of how you can present this interaction. In the example below I am enabling editing for the elements <p> and <h2> and you can use the selectors you find suitable as well as perform database persistence by performing an ajax post for your php.

let editar = function(elemento) {
  let original = elemento;
  original.hide();

  let editor = $('<input type="text" />').insertAfter(original);
  editor.val(original.text());
  editor.on('blur', () => {
    let novoConteudo = $(editor).val();
    original.text(novoConteudo);

    // Aqui você poderia persitir o conteúdo no banco
    // via ajax

    $(editor).detach();
    original.show();
  });
  editor.focus();
};

$(document).ready(() => {
 
 //Seletor dos elementos que você deseja que sejam editaveis
 let containers = $('body').children('p, h2')
 
 $.each(containers, (index) => {
    let elemento = containers[index];
    //adiciona o evento de click
    $(elemento).on('click', () => {
      editar($(elemento))
    });

    //altera a aprencia do cursor
    $(elemento).hover(
      function() {
        $(this).css('cursor', 'pointer');
      },
      function() {
        $(this).css('cursor', 'auto');
      }
    );
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<body>
  <h2>Titulo original</h2>
  <p id='teste'>Texto original</p>
</body>
<html>

  • Perfect Leandro. Thank you very much!

  • 1

    @Fox.11 is far from perfect, but I think it’s a starting point for you to work up.

Browser other questions tagged

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