0

I have a page that allows users to post comments via jquery's ajax. These comments can also be edited. The problem is that after i type a comment and click "edit" the jquery is not executed (ideally a modal should popup). When i type a comment, refresh and then click "edit" the jquery runs perfectly. I have been trying to debug this myself for quite some time, but I don't see why the refresh makes the difference.

JQUERY:

//this part takes the comment and enters it into a mysql database and 
//then appends the comments div to write the new comment.  This code works.
$('#answerCommentTextarea').keypress(function(e) {
if(e.which == 13) 
{
    if ($.trim($(this).val()) == "")
    {
        $('#nocomment').modal('show');
    }
}
else 
{           
    var comment = $('#answerCommentTextarea').val();
    $.post('../writeanswercomment.php' , 
        {
            comment: comment , 
            user: <?php echo $_SESSION['id']; ?>, 
            questionid: <?php echo $_GET['q']; ?>},
            function(response)
            {               
                $('#answerCommentContainer').append(response);
                $('#answerCommentTextarea').val('');
            }
        });
}

This is the output of writeanswercomment.php. This is the BAD code. When i click the edit button here, the below Jquery does not run. Even the preventDefault() doesnt work because # appears in the url

echo "<div class='singleComment'>
<b>
    <a href='../profile.php?p=$user'>$name</a>
</b>".
$comment." 
<input type='hidden' value='$qid' name='hiddenComment' class='hiddenComment' />
<a href='#' style='color: orange;' class='editComment'><b>Edit</b></a>
<div class='commentBar'>Just now</div>
</div>";

This is the Jquery that works after the refresh, but does not work when the comment is entered and edited without any refresh.

$('.editComment').click(function(e)
{
    e.preventDefault();
    var s_comment = $(this).prev('.hiddenComment').attr('value');
    $.post('../editcomment.php' , {comment: s_comment} , function(response)
    {
        $('#modalEditComment').val(response);
        $('#editCommentModal').modal('show');
    });         
});

If the comment is not entered via Jquery's ajax then it was previously entered and stored in the database. This is the code that runs when a comment has already been entered. (This is the GOOD code. When i click the edit button, the above Jquery runs perfectly).

echo "<div class='singleComment'>
<b><a href='/profile.php?p=".$comment_user[$a]."'>".$name[$a]."</a></b>".
$comment[$a]".
<input type='hidden' value='".$comment_id[$a]."' name='hiddenComment'
class='hiddenComment'/>";
$current_time=time();
if ($_SESSION['id'] == $comment_user[$a] && $current_time - $comment_time[$a] <60)
{
    echo " <a href='#' style='color: orange;' class='editComment'><b>Edit</b></a>";
$periods = array(
            "second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
$now = time();
$difference     = $now - $comment_time[$a];
$tense         = "ago";
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) 
    {
    $difference /= $lengths[$j];
}
$difference = round($difference);

    if($difference != 1) 
    {
    $periods[$j].= "s";
}

    echo "<div class='commentBar'>".$difference." ".$periods[$j]."ago</div>
</div>";
2
  • 1
    Some proper indentation would be great... Commented Jan 9, 2012 at 3:09
  • @ThiefMaster i will go back and edit the indentation. sorry. did i explain what my problem was? it's kinda hard to explain because it involves a lot of code Commented Jan 9, 2012 at 3:14

2 Answers 2

1

You don't need to use live() to attach your keypress event. Here, you need to attach delegated event handlers on content dynamically added to a page. You can use live(), delegate(), or on(). But as you can see:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). [source]

So, you can use:

$("#answerCommentContainer").on("click", ".editComment", function(){
    //your code here
});

Edit:

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().

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. [source]

Here, you append your ajax response to this element #answerCommentContainer, wich is "guaranteed to be present at the time the delegated event handler is attached". That's why I use it to bind the click event. You can bind any element (as the document), but I usually choose the closest parent, to prevent event from bubbling when it's not needed.

Sign up to request clarification or add additional context in comments.

2 Comments

did you mean answerCommentTextarea?
THAT WORKED! you are the man. i spend 12 hours trying to do this. thanks
0

maybe you try your keypress and click events using live() function.

$('#answerCommentTextarea').live('keypress', function(e) {
...
    if(e.keyCode == 13){
...
}

and

$('.editComment').live('click', function(e){
...
}

I'm not sure if this is the problem, give it a try)

3 Comments

In jQuery you should always use e.which - it's the normalized version of either e.which or e.keyCode of the original event.
@acute my enter function is working fine. The problem is that after the comment is put into the database and appened into the comments div. I can't click edit. But I can after i refresh. I'm curious as to why this is, because the append code and the code after refresh are very similar
@ThiefMaster: as far as I know e.which doesn't work while using live('keypress'), that's why e.keyCode is used.

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.