简体   繁体   中英

How to get textarea value from many different textarea with the same IDs

How can I get a value from many different textarea tags with same IDs using jQuery? I also need to allow the user a choice of which textarea he/she wants to add a comment, and then get the comment.

This is my HTML

<div class="container">
    <div class="wall_post">
        <p>First Post</p>
        <textarea id="user_comment" class="form-control" placeholder="Type your comment here"></textarea>
    </div>
        <div class="wall_post">
            <p>Second Post</p>
        <textarea id="user_comment" class="form-control" placeholder="Type your comment here"></textarea>
    </div>
        <div class="wall_post">
            <p>Third Post</p>
        <textarea id="user_comment" class="form-control" placeholder="Type your comment here"></textarea>
    </div>
        <div class="wall_post">
            <p>Fourth Post</p>
        <textarea id="user_comment" class="form-control" placeholder="Type your comment here" ></textarea>
    </div>
</div>

And this is my jQuery so far

This jQuery only prints out the first textarea value, but is ignoring the others.

$(document).on('keydown', function(e) {
    var targetInput = $('#user_comment');

    if(!targetInput.is(document.activeElement)) {
        alert('Typed while not focused on #myInput!');
    }else{
        if(e.which == 13){
        alert(targetInput.val());
         targetInput.val('');

        }
  }
}); 

Thank you in advance!

Ids must be unique. You can rather use classname.

Also you can use target to get current keydown element:

$(document).on('keydown', function(e) {
 var targetInput = $(e.target);
   if(!targetInput.is('textarea')) {
      alert('Typed while not focused on #myInput!');
   }else{
     if(e.which == 13){
       alert(targetInput.val());
       targetInput.val('');
    }
}}); 

Working Demo

As ID's are expected to be unique jQuery will return the first element, not a list of all with that ID.

To access all of your textareas you could use this selector (assuming there is only a single text area with each wall_post div:

$('.wall_post textarea')

You could bind your keydown event to this instead as well:

$(document).on('keydown', '.wall_post textarea', function(e) {
    // do whatever you need to with this textarea
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM