AlexM
AlexM

Reputation: 325

li tag in html shows no action when clicked using jquery

After having tried to figure out for one day why this simple piece of code is not working, I have to ask someone else because I just can't figure it out.

HTML:

<li><button id="button-middle" type="button"></button>
<ul id="list-middle" style="display: none;"></ul>
</li>

Jquery:

$(document).ready(function () {
    $('#button-middle').click(function () {
        $.post('file.php', {data_1: $('#select_1 option:selected').text(), data_2: $('#select_2 option:selected').text()}, function (data) {
            $('#list-middle').html(data);
        });
    });
});

$(document).ready(function () {
    $('#list-middle li').click(function () {
        alert('test');
    });
});

The button is part of an ul that contains three button, this one is the middle one. file.php just consists of a simple echo with the sent data inserted. The output is as expected (li tags in an ul), but when I click one of these li tags, nothing happens. Why is that?

Just to be super clear, here is the php file:

if (isset($_POST['data_1']) and isset($_POST['data_2'])) {
        $data_1 = $_POST['data-1'];
        $data_2 = $_POST['data_2'];
        echo '<li data-value="right" id="to_right"><span>&#8594;&nbsp;Von '.$data_1.' nach '.$data_2.'</span></li>
                                <li data-value="left" id="to_left"><span>&#8594;&nbsp;Von '.$data_2.' nach '.$data_1.'</span></li>
    ';
    }

I appreciate any help becuase after more than a day, this is driving me nuts.

Upvotes: 0

Views: 552

Answers (2)

Dmitriy
Dmitriy

Reputation: 93

I think that the problem is that list itemss are added dynamically, so on click event is not attached to them. Because it fired only once on document ready.
You might try this:

$('body').on('click', '#list-middle li', function() {
    // do something
});

If I recall correct, it's called Event Bubbling.

Upvotes: 1

grupowebex
grupowebex

Reputation: 185

When you bind actions, like click actions, you should define a context (document in this case) in order to work with dynamic loaded content. Think it should work:

$(document).on('click','#list-middle li', function(e){ alert('test'); });

Upvotes: 2

Related Questions