0

My code below was used to retrieve records from a loop using JavaScript. Everything works fine. Each of the records button has a unique id that when click should alert users_id in a Bootstrap Modal popup.

The problem is that the looped button that contains users_id is not alerting anything when each button is clicked.

Below is the code for retrieving records in JavaScript along with Bootstrap modal button:

<script>
    $(document).ready(function () {
        $.post('users.php', function(response){
            $.each(JSON.parse(response).items, function(i,v) {
                $('.userslist').append('<span>'+v.id+'</span> <a href="#myModal" id="'+v.id+'" class="modalLink"  data-toggle="modal" data-target="#myModal">Profile</a>');
            });
        });
    });
</script>

Below is the code for posting the users_id and then alert it:

<script>
    $(document).ready(function(){
        $(".modalLink").click(function() {
            var id = $(this).attr("id");
            alert(id);
            var dataString = 'id='+ id;
            $.ajax({
                type: "POST",
                url: "ajax_modal.php",
                data: dataString,
                cache: false,
                success: function(data) {      
                    $("#rmm").html(data);
                } 
            });
        });
    });
</script>

but if I take the Modal button outside the retrieve records in a javascript loop it will alert users_id and everything will work fine as in code below

<a href="#myModal" id="'+v.id+'" class="modalLink"  data-toggle="modal" data-target="#myModal">Profile</a>

Can someone help me make each of the JavaScript looped button to post its own unique users_id and then alert it in a Bootstrap modal popup. I have attached a screen shot of the result obtained from the JavaScript loop.

Example Result

Thanks

Mamun
  • 66,969
  • 9
  • 47
  • 59
akwaeze
  • 71
  • 7

1 Answers1

0

If I understand your question properly;

Try changing

$(".modalLink").click(function() {

to

$(document).on('click', '.modalLink', function() {

Without seeing the rest of your code or a working fiddle, I suspect your content is dynamic and JQ cannot bind the click handler, simply because there is no content to bind to. this answer does a good job of explaining the difference between .on and .click.

If you get the expected result, I would drop the document selector and use the closest parent static element.

Mark Carpenter Jr
  • 812
  • 1
  • 16
  • 32