0

I'm trying to create a function that starts when you click on a specific link in a listview. The issue is that event doesn't seem to fire when you click the link. The list is created dynamically. I'm not sure if that causes an issue.

    <label for="listviewForLastTenCalls">Last Ten Calls:</label>
    <ul data-role="listview" id="listviewForLastTenCalls">
    </ul>
<script>
   $('#listviewForLastTenCalls li').click(function(){
        //alert('click event handler fired');
</script>
3
  • some more HTML please Commented Jun 25, 2013 at 15:25
  • Ya, post relevant HTML code, there is no LI in your actual code... Commented Jun 25, 2013 at 15:26
  • $(document).on('click', '#listviewForLastTenCalls li', function () { Commented Jun 25, 2013 at 15:27

6 Answers 6

6

Demo

<ul data-role="listview" id="listviewForLastTenCalls">
  <!-- items dynamically generated -->
</ul>

JS

$(document).on('click', '#listviewForLastTenCalls li a', function () {
 // code
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help omar that works. I forgot that the event handler would try to latch on an li that didn't exist until at document load.
@Matt you're welcome, please check the demo for further details :)
1

The issue is you are adding the click listener after you have created the list. When you first create the listener there is nothing for it to listen to. You need to add the on click event after you add the <li>

1 Comment

or better, using delegation
1
$('#listviewForLastTenCalls li a').click( function () {
 // code
});

Comments

0

I hope this is not your fully markup,...

  <label for="listviewForLastTenCalls">Last Ten Calls:</label>
    <ul data-role="listview" id="listviewForLastTenCalls">
    </ul>

<script>
   $('#listviewForLastTenCalls li').click(function(){
        //alert('click event handler fired');
   }); //<--
</script>

And if the list is creadted dynamically, you have to attach the event, after list was created...

Comments

0

You have to do event delegation for dynamically added elements.

    $('"#listviewForLastTenCalls"').on("click",'li' ,function(){
       alert('triggered');
    });

And why on() works ??

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Comments

-1

Something like this:

$(function() {
   $("#listviewForLastTenCalls li").on('click', function() { alert('clicked');  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.