Pregunta

I'm trying to creat simple comment system for wall posts (like facebook wall) and I'm using load more button to show 10 more posts from database everytime "show more" button clicked ... and for every post there is comment textarea, to add comment I'm using the "Enter keypress function" ..

Keypress event works as desired before ajax call.

When user activates the load more posts event, the keypress event no longer functions, I checked page source code, the posts loaded source code not found on the page but this posts appear in browser !!

add comment function :

    $(function() {
    $('.comment-form').keypress(function(event) {
        if (((event.keyCode || event.which) == 13) && !event.shiftKey) {
            // My ajax request here
                }
            });
    });

load more function :

    $(function() {
        //More Button
        $('.more').live("click",function() {
            var ID = $(this).attr("id");
            if(ID) {
                $.ajax({
                    type: "POST",
                    url: "{$url}/ajax.php",
                    data: "loadmore="+ ID, 
                    cache: false,
                    success: function(html) {
                        $("#loadmore").append(html);
                    }
                });
            }
            return false;
        });
    });

HTML :

        <div class="message">
        $Message
        </div>
        <div class="commenter">
        <textarea id="$id" class="comment-form" type="text" placeholder="Write comment..." maxlength="1000"></textarea>
        </div>

I'm beginner please help :)

¿Fue útil?

Solución

Use following code to have keypress event bind for all the future html along with current html in DOM -

$('.comment-form').on('keypress', (function(event) {
    if (((event.keyCode || event.which) == 13) && !event.shiftKey) {
        // My ajax request here
    }
}));

Otros consejos

The html content loaded via ajax won't have the event attached to it, it's new. Attaching the event is not retrospective. You will need to run the function that attaches the events to the new HTML.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top