On("Click") Javascript does not work

Asked

Viewed 119 times

2

I made a script to get the value of an element that is generated in php, whenever this element is clicked but it is not working

<script>
    $('.collection-item').on('click',function(){    
        var  idA = $(".collection-item").val();  
        alert("tete");  
        $.ajax({ 
            url: 'Chamadas/listarMunicipios.php', 
            type: 'POST', 
            data: { id: idA},
            success: function(data) { 

                window.location.reload(); 
            } 
        }); 

    });
</script>

Element

echo '<a href="#!" value="" class="collection-item">TESTE</a>';
  • This element is added dynamically ?

  • it is added in a foreach, in case are several equal elements with only different text, they also have the same class, the intention is that when any of these elements are clicked I can get the value of them

  • 2

    Try: $(document).on('click', '.collection-item', ...

  • It worked thanks :D, put as an answer for me to mark as correct

  • There is already a question on the subject, so vote there on the answer!

1 answer

0


Just in case someone comes to this page..

the code is correct as exemplified by min below:

$('.collection-item').on('click',function(){    
        var  idA = $(".collection-item").val();  
        alert("funcionou");  
        $.ajax({ 
            url: 'http://www.json-generator.com/api/json/get/cdYItaXpvm?indent=2', 
            type: 'GET', 
            success: function(data) { 

                console.log(data);
            } 
        }); 

    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#!" value="" class="collection-item">TESTE</a>

The problem is that it is generating code using php, and the script needs to reference the document, so it is necessary to use :

$(document).on('click', '.collection-item'

in the jquery code.

You can also do it if you manage this code within a function

// A $( document ).ready() block.
$( document ).ready(function() {
   //codigo do clik aqui dentro
});

or using the short version:

// Shorthand for $( document ).ready()
$(function() {
    //codigo do clik aqui dentro
});

link to a question and answer already created previously

What is the difference between . on("click", Function() {}) and . click(Function() {})?

Another interesting thing

It is not recommended to use php to generate the view, there are new architecture standards that we advise to create something more modular, separating the front of the backend, leaving everyone independent. a well-used standard is restAPIinsert link description here

Browser other questions tagged

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