Problems creating a reusable modal

Asked

Viewed 131 times

0

  • HTML

//I take what’s inside the class observacoes and play for a textarea within the modal

                <td>
                    <div class="observacoes">teste</div>
                    <button class="btn btn-default btn-modal-comentario" data-obs-id="{{ $lista->user_id }}">Adicionar/Atualizar Comentários</button>
                </td>
  • Meu Modal

// Inside it will be created a button dynamically (Atualizar Comentário and will have a textarea with the text of the remarks and will be editable)

<div class="modal fade" tabindex="-1" role="dialog" id="modal-1">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body">
                <div class="modal-conteudo"></div>
            </div>
            <div class="modal-footer">
                <div class="modal-buttons">

                </div>
            </div>
        </div>
    </div>
</div>
  • Jquery

//An update button will be created dynamically and a textarea within the modal

        $(document.body).on("click", "#btn-modal-update", function(){
            var $modal = "#modal-1";
            alert($($modal).find("textarea").text());
            $.ajax({
                headers: {
                    'X-CSRF-Token': $('input[name="_token"]').val()
                },
                url: "{{ URL::to('lista-contatos/update') }}",
                data: {
                    "id": get_id,
                    "observacao": $($modal).find("textarea").text()
                },
                type: "POST",
                success: function(result){

                }
            });
        });
        $(document.body).on("click",".btn-modal-comentario", function(){
            var $modal = "#modal-1";
            get_id = $(this).data("obs-id");
            var obs = $(this).closest("td").find(".observacoes").text();

            $($modal).find(".modal-body").html("<textarea class='form-control' id='teste'>"+obs+"</textarea>");
            $($modal).find(".modal-footer").html("<button class='btn btn-primary' id='btn-modal-update'>Atualizar Observação</button>");
            $($modal).modal('show');

        });

The problem is that you are not getting the updated value correctly after you type anything into the textarea, the generated text is always "teste".

1 answer

0

The problem is occurring because you are never updating the original html, so you are always getting the same value...

Below is the corrected code and working, see explanations in the code comments:

// definir uma global para guardar o elemento de retorno
var observacoes;

         $(document.body).on("click", "#btn-modal-update", function(){
            var textarea = $(this).parents('.modal').find("textarea").text(); // selecione o textarea no modal em que esta o botão clicado, caso reutilize o código ou modifique o id do modal isso não será problema
            console.log(textarea);
            $.ajax({
                headers: {
                    'X-CSRF-Token': $('input[name="_token"]').val()
                },
                url: "{{ URL::to('lista-contatos/update') }}",
                data: {
                    "id": get_id,
                    "observacao": textarea
                },
                type: "POST",
                success: function(result){
                  // atualizar o valor no html original
                  observacoes.html(textarea); // variável global com o elemento original
                }
            });
          // deixar aqui fora só aqui no teste       
          observacoes.html(textarea); // variável global com o elemento original         
        });
        $(document.body).on("click",".btn-modal-comentario", function(){
            var $modal = $('#modal-1'); // guarde na variável o elemento e não a str de seleção
            get_id = $(this).data("obs-id");
            observacoes = $(this).siblings(".observacoes"); // guardar o elemento na variável global para atualizar depois
            $modal.find(".modal-body").html("<textarea class='form-control' id='teste'>"+observacoes.html()+"</textarea>");
            $modal.find(".modal-footer").html("<button class='btn btn-primary' id='btn-modal-update' data-dismiss='modal'>Atualizar Observação</button>");
            $modal.modal('show');

        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="col-xs-12">
  <h1></h1>
<div class="well">
                    <div class="observacoes">teste</div>
                    <button class="btn btn-default btn-modal-comentario" data-obs-id="{{ $lista->user_id }}">Adicionar/Atualizar Comentários</button>
</div>
</div>

<div class="modal fade" tabindex="-1" role="dialog" id="modal-1">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body">
                <div class="modal-conteudo"></div>
            </div>
            <div class="modal-footer">
                <div class="modal-buttons">

                </div>
            </div>
        </div>
    </div>
</div>

Browser other questions tagged

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