I developed a page using codeigniter framework. Following is the part of a code in the controller. This creates few sets of buttons and input fields. When I click on each button values should added to the relevant input field. Everything works fine. But the problem is I have to click twice on the button. Once I click twice then values start to appear. And if I continue to click on other buttons then values generated in relavent input fields by one click. It need double click for the first button click. (Not for the first button of the order. I need to click twice for even start with button in the middle).
Also if I click two different buttons(each button 1 time). Then values will be added to the both input fields with the second click.
Also according to direction in a previous answer of the stackoverflow question I tried changing it to
$test .= '<input type="button"
instead of
$test .= '<button
But there was no luck. I'm really thankful if someone can give me a clue for this issue.
foreach ($data as $c) {
foreach ($c as $value) {
//There are some codes here
//But there are no <form> elements in this area.
$test .= "  <a>reply</a><br>";
$test .= '<input type="text" id="new_reply' . $value['id'] . '" class="form-control">';
$test .= '<button data-comment-id="' . $value['id'] . '" onclick="test_function(this);">Reply</button>';
}
}
echo json_encode($test);
And here is my js function. Please note that this is not the end purpose of this function. I changed it to something very simple to identify the issue. Also to convey my issue.
$(document).ready(function(){
test_function();
})
function test_function(reply){
$("button").click(function() {
var comment_id = reply.getAttribute("data-comment-id");
if(comment_id){
var inputbox_id = "new_reply" + comment_id;
document.getElementById(inputbox_id).value ='test value';
}
});
}
and here is a sample image of the page

Edit 1
In my view file I have code like this.
<div id="page_content" class="text-dark"></div>
then using ajax method I add the content like this
$('#page_content').html(response);
So I noticed that actually the div element is only clicked when I click the button.
I used these function to test this
$(document).ready(function(){
Insert_record();
view_content();
insert_reply(this);
})
function insert_reply(reply){
$("div").click(function() {
console.log("USA");
$("button").click(function() {
//insert_reply(this);
console.log("Argentina");
});
});
}
When I click a button once then result was this.
When I click for the second time then console changed to this.

