Jeff Gu Kang
Jeff Gu Kang

Reputation: 4879

Click event for dynamically generated elements on listview

I tried to apply click event to elements dynamically generated.

This example is work well. http://jsfiddle.net/PzSYM/361/

But my code does not work. http://jsfiddle.net/EurT4/8/

This is same code with above link.

HTML

<ul id="timer_listview" data-role="listview">
    <li class="timerList">
        <button>on</button>
        <span class='status'>play</span>
    </li>
    <li class="timerList">
        <button>on</button>
        <span class='status'>play</span>
    </li>
    <li class="timerList">
        <button>on</button>
        <span class='status'>play</span>
    </li>
</ul> </div>

JavaScript(Jquery)

var counter = 0;

$('#addButton').click(function () {
    $('#console').text('new line added');
    var text = '<li class="timerList"><button>new' + (++counter) + '</button><span class="status">play</span></li>';
    $('#timer_listview').prepend(text);
    $('#timer_listview').listview("refresh");
});

var play = 'play';
$('.timerList').on('click', 'button', function () {
    $('#console').text('clicked');

    var status = $(this).parent().find('span.status');
    if (status.text() == play) {
        status.text('pause');
        $('#console').text('Status Changed');
    }
});

CSS

.status { display: none; }

I got a panic why it does not work. :( Thank you for reading my question.

p.s Anytime welcome to edit my writing.


UPDATE I solved this problem. http://jsfiddle.net/EurT4/10/ . The point is using closest parent. Thanks to Milind Anantwar.

Upvotes: 0

Views: 282

Answers (2)

Kamlesh Delat
Kamlesh Delat

Reputation: 138

<script>
function onclickButton(e)
{
   alert(e+"Clicked");
}
</script>
<button onclick="onclickButton(1)">Button1</button>
<button onclick="onclickButton(2)">Button2</button>
<button onclick="onclickButton(3)">Button3</button>
<button onclick="onclickButton(4)">Button4</button>

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You are adding elements .timerList dynamically. You need to use:

$('#timer_listview').on('click', '.timerList', function() {
        $('#console').text('clicked');              

var status = $(this).parent().find('span.status');
if (status.text() == play) {     
    status.text('pause');        
    $('#console').text('Status Changed');              
}});

Upvotes: 2

Related Questions