I have such a template when the user clicks the edit glyphicon, it will prompt a form for further editing:
<div class="post-menu pull-left">
<a class="editCommentLink" href="#">
<span id="{{ comment.id }}" class="glyphicon glyphicon-edit" aria-hidden="true">edit </span>
</a>  
<a class="delCommentLink" id="{{ comment.id }}" href="#">
<span id="{{ comment.id }}" class="glyphicon glyphicon-trash" aria-hidden="true">delete</span>
</a>
</div>
I employed ajax to send the get request and update the content with $commentNew.html(commentEditForm)
;
<script>
$(document).ready(function(){$(".editCommentLink").on("click", function(e) {
e.preventDefault()
var comment_id= $(e.target).attr("id")
// Retrieve the top node of comment-right
var $commentRight= $(e.target).closest(".comment-right")
$.ajax({
type: "GET",
url: `/ article/comment/edit /${comment_id}`,
success: function(data){
var ret=JSON.parse(data)
var body=ret['body']
var commentEditForm= `
<form action="#" method="post" > {% csrf_token % }
< div class="form-group" >
< textarea class="form-control" name="comment" id="editComment${comment_id}" >${body} < /textarea >
< button class="btn btn-primary" id="editSubmitBtn" > Save Edits < /button >
<a href="#" > cancel < /a >
< / div >
< /form >
`
var $commentNew= $commentRight.find(".post-text");
$commentNew.html(commentEditForm);
}, // success
});//end of ajax
})//end edit click
</script>
However, there's no feedbacks when I am triggering button id="editCommentBtn"
to submit the form data,
});//end of ajax
})//end edit click
$(document).ready(function (e) {
//still in edit click event
$("#editCommentBtn").on("click", function (e) {
e.preventDefault();
alert('button clicked');
...
});//submit click event
})
I experiment to solve the problem, what confused me is that if I change $(".editCommentBtn")
to its grandparent $(".post-text")
, the browser alert me ('button clicked'),
I attempted to break the bulk of var commentEditForm=
to single elements like:
$newForm = $('<form action="#" method="post" > {% csrf_token % } < /form >');
$newFormGroup = $('< div class="form - group" >< / div >');
$newText = $('< textarea class="form-control" name="comment" id="editComment${comment_id}" >${body} < /textarea >');
$newSubmit = $('< button class="btn btn-primary" id="editCommentBtn" > Save Edits < /button >')
$(.post-text).append($newForm);
$newForm.append($newFormGroup);
$newFormGroup.append($newText);
$newText.after($newSubmit);
There are many manual labors,
How to solve the problem elegantly?