Ben
Ben

Reputation: 305

Target and update dynamically created content using AJAX

I am trying to create a question/answer system where a user can reply to existing questions. The question system is correctly posting and displaying to the database, but I am having difficulties replying to dynamically created questions.

To save space here is the code that is failing

$(document).ready(function() {
//make sure it was the postReply button
    $("#postReply").on("click", function(){
        //get the questionID the user just clicked on
        var questionID=$(this).val();
        //hide the reply button
        $("#postReply").hide();
        //show the reply framework
        $('.reply').append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>');
    });
});

Called from this line within a loop:

echo '<p><button type="submit" id="postReply" value='.$questionID.'>Reply</button></p> ';
echo '<div class="reply" id="reply'.$questionID.'">';

The issue that I hit is that I am updating and adding the div to every single question because of the .reply is incorrectly targeting. I can't seem to get it to target the questionID that was clicked. I have tried testing it with alerts but only the most recent question button is parsing to the script.

I can only hide the button from the most recent comment added.

This is the output of the HTML source that is being created from the SQL query

<p>Question ID: 34 Title: z Description: zz Date Posted:2017-08-04 05:31:28</p>
<p><button type="submit" id="postReply" value=34>Reply</button></p> 
<div class="reply" id="reply34"></div>

When clicking the Reply button to the above question the code should look something like:

<p>Question ID: 34 Title: z Description: zz Date Posted:2017-08-04 05:31:28</p>
<div class="reply" id="reply34">
    <div class="replycontent">
        <p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p>
        <p><button id="postAnswer" type="submit">Post Answer</button></p>
    </div>
</div>

Upvotes: 0

Views: 38

Answers (1)

K&#233;vin Bibollet
K&#233;vin Bibollet

Reputation: 3623

I am not sure to really understand the problem, but try replace this:

$('.reply').append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>');

by this:

$('#reply' + questionID).append('<div class="replycontent"><p><textarea name="answer" id="answer" placeholder="Enter your answer"></textarea></p><p><button id="postAnswer" type="submit">Post Answer</button></p></div>');

Your fields have all a different ID attribute, so you can use it.

And to hide your button, since they have all the same ID, your selector can look like $('#postRelpy[value="' + questionID + '"]').

Upvotes: 1

Related Questions