Muhammad Umar
Muhammad Umar

Reputation: 11782

Dynamically changing the text of Label on Click in jquery

My web html has following code

<script  src="js/jquery.flexslider.js"></script>
<script  src="js/jquery.rings.js"></script>

Contents of jquery.rings.js are :

$('input[type="image"]').click(function()
{
   $ring = $(this).data('my-info');
   $('label#ringName').text($ring['ringSetName']);
});


/***************************************************/

My Html code is fetching an array of rings

$db = new db();
$rings = $db->query("SELECT * FROM rings");

On runtime i am adding images in a slider as follow

<div class="albums-div">
    <ul class="slides">

        <?php



 foreach($rings as $ring)
          {
             echo '<li> <input type="image" src="' . $ring['ringThumbNailImagePath'] . '" name="checked" value="" data-my-info="' . $ring . '" width="150" height="150" /></li>';
           }   



         ?>
    </ul>
</div>

The problem is , on Clicking the image nothing happens, the JS script seems not to be getting called.

tHE JS function should set the text of a label defined in the code as

What could be the problem?

Upvotes: 0

Views: 632

Answers (2)

Felix
Felix

Reputation: 38112

Try to use event delegation for dynamically added elements:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$('body').on('click','input[type="image"]',function()
{
   $ring = $(this).data('my-info');
   $('label#ringName').text($ring['ringSetName']);
});

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You need event delegation for dynamically added elements:

$(document).on('click','input[type="image"]',function()
{
  $ring = $(this).data('my-info');
  $('label#ringName').text($ring['ringSetName']);
});

Upvotes: 1

Related Questions