1

code:

<script>
  $(document).ready(function(){
    $(".check").click(function(){
      comment = $(".comment2").val();
      alert(comment);
    });
  });
</script>

<?php        
  $sql = "select * from enquires2";
  $result = mysqli_query($link,$sql);
  while ($row = mysqli_fetch_array($result)) 
  {
    echo "<tr>
            <td>
              <input type='checkbox' class='check' id='chk".$row['id']."' name='chk' value=".$row['id'].">
            </td>

            <td>
              <input type='text' name='comment2' class='comment2' id='comment2_".$row['id']."' value='' />
            </td>
          </tr>";
  }
?>

In this code when I enter text inside comment2 input field and then check checkbox it alert only 1st row value but when I enter second textbox and then again check checkbox it show nothing. So, how can I get multiple textbox value onclick on checkbox ? Please help.

Thank you

kevin
  • 234
  • 2
  • 14
  • since you add dynamically use event delegation like `$(document).on("click",".check",function(){` but i suggest use `change` for checkbox – guradio May 10 '17 at 06:36
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – guradio May 10 '17 at 06:37
  • Sorry, you'r doing same as am I do no difference between your and mine code @guradio – kevin May 10 '17 at 06:42
  • how is `$(document).on("click",".check",function(){` the same with `$(".check").click(function(){` ? – guradio May 10 '17 at 06:43
  • because it return same thing as $(".check").click(function(){ – kevin May 10 '17 at 06:46
  • use `comment = $(this).parent().next().find(".comment2").val();` – guradio May 10 '17 at 06:48
  • I want that it give different value of comment2 input field when I click on different checkbox – kevin May 10 '17 at 06:48
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/143834/discussion-between-guradio-and-kevin). – guradio May 10 '17 at 06:49

1 Answers1

0

Problem is, that both the elements are of class .comment2, which means the $(".comment2") creates an array for you, and the .val() only gets the value of the first element in the array.

You have to use a more unique value (since ID's not always start at 0, a simple counter thingy wont work)

May I suggest

<script>
    $(document).ready(function(){
        $(".check").on("click", function(){
            var $id = $(this).val();
            comment = $("#comment2_" + $id).val();
            alert(comment);
        });
    });
</script>

Using $(this).val() to get the id value saved in your checkbox, and concatenating that with the ID comment2_x to get the content of the input box