Recover jQuery date variables

Asked

Viewed 204 times

1

I have the following button:

<button type="button" class="btn btn-default" data-toggle="modal" data-target="#abrir-imagem" data-pasta="interno_fotos" data-imagem="139379939.jpg">Abrir Imagem</button>

I need to retrieve it through Ajax. And I did it this way:

    $('#abrir-imagem').on('show.bs.modal', function(e) {
        var pasta = $(this).data("pasta") 
        var imagem = $(this).data('imagem');
        $("#imagem").html("<img src='"+BASE_URL+"assets/uploads/"+pasta+"/"+imagem+"'>");
    });

It opens the modal correctly, however, the image does not appear. It says that the two variables are undefined. What is the right way to seek them?

2 answers

2

Exchange the Javascript code for this:

$('#abrir-imagem').on('show.bs.modal', function() {
  var pasta = $(this).attr('data-pasta');
  var imagem = $(this)attr('data-imagem');

  $("#imagem").html("<img src='"+BASE_URL+"assets/uploads/"+pasta+"/"+imagem+"'>");
});

1


It is not working because your call 'makes no sense', you are informing $(this) to catch a attr other element.

In this passage:

$('#abrir-imagem').on('show.bs.modal', function(e) {

You are saying "when the id open-image modal starts to appear shoot", ie you will not find the data-attrs of buton with $(this) when button is not $(this).

Simply add a classname identifier to the button, and fetch the data-attr through it, as in the following example:

$('#abrir-imagem').on('show.bs.modal', function(e) {
        var pasta = $('.open-modal-btn').data("pasta") 
        var imagem = $('.open-modal-btn').data('imagem');
        //$("#imagem").html("<img src='"+BASE_URL+"assets/uploads/"+pasta+"/"+imagem+"'>");
        console.log('Pasta:' + pasta + '| Imagem: ' +imagem )
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button type="button" class="open-modal-btn btn btn-default" data-toggle="modal" data-target="#abrir-imagem" data-pasta="interno_fotos" data-imagem="139379939.jpg">Abrir Imagem</button>

<!-- Modal -->
<div id="abrir-imagem" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

Browser other questions tagged

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