0

There is a probelm in getting a textbox value using jquery it is store in while loop following is my design code

<?php
 while($raw=mysqli_fetch_array($result))
 {
 ?>
    <input type="text" name="comment" id="comment" class="comment"/>
    <input type="button" name="btncmnt" id="btncmnt" class="btncmnt"/>
 <?php
  }
?>

Here is my jquery code

<script type="text/javascript">
    $(document).ready(function(){
        $(".btncmnt").click(function(){                
            var comment=$(this).val(".comment");
            alert(comment);
            //this will be display only first textbox value
        });
    });
</script>

When i click another button of the loop then it will be display first texbox value please give me ans to get current textbox value thank in advance

1
  • Your question is incomplete or missing some syntax. like there is no value assigned to textbox within while loop. Commented Jan 25, 2017 at 9:01

1 Answer 1

1

Firstly note that your PHP loop will be creating invalid HTML as you are generating multiple elements with the same id attribute. As you don't seem to be using it, you should remove it:

<?php while($raw = mysqli_fetch_array($result)) { ?>
  <input type="text" name="comment" class="comment"/>
  <input type="button" name="btncmnt" class="btncmnt"/>
<?php } ?>

Your issue is because your use of val() is incorrect. You need to first use DOM traversal to find the related .comment element, then use the getter of val() to retrieve its value, like this:

$(".btncmnt").click(function(){                
  var comment = $(this).prev(".comment").val();
  console.log(comment); 
});
Sign up to request clarification or add additional context in comments.

4 Comments

how can i get value of the textarea insted of textbox
In exactly the same way. Get a reference to the element and call val()
i used that bt result will be undefined how can solve that
In that case you haven't selected the element properly. I'd suggest starting a new question about that as this one is about getting the value from a related input and nothing to do with textarea elements

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.