Shavkat Shavkat - 5 months ago 32
PHP Question

JQuery: Get jquery val on keypress from multiple ids with the same name

Hope anybody can help with this.
I have a php foreach running, where I get multiple acticles from the database:

@foreach ($articles as $article)
<div class="article">
<input id="comment" type="text" class="materialize-textarea" placeholder="Add comment"/>
</div>
@endforeach


Let's say i have 2 or more articles in the database. So on the html side the div gets duplicated and i have multiple divs with the same id.

Next i want jquery to get the input value. Here's the sample code

$("#comment").each(function()
{
$(this).keypress(function(e)
{if (e.which == 13)
alert('works');
});
});


The result: it works perfectly on the first record pulled from database(first article). on the second article and onward the JavaScript doesn't trigger at all.
I understand the problem it's because jQuery reads the first div only. I check some solutions online, but nothing really worked for me. The most logical solution seemed to be putting .each in the function. But the result is the same. The first articles triggers JavaScript perfectly, the rest don't.

Notes: If the php code looks strange please ignore it, it's on laravel framework. Nonetheless, it executes correctly.
The code presented here only shows the logic of the application and is not the actual code.

Answer

The id attribute should be unique, since it's using for uniquely identifying an element. The id selector only selects the first element which have the id, so use class instead for group of elements.

@foreach ($articles as $article)
   <div class="article">          
       <input class="comment" type="text"  class="materialize-textarea"  placeholder="Add comment"/>
       <!-------^---- set class instead of `id` ---------------------------------------------------> 
   </div>
@endforeach

Then there is no need to iterate over them using each(), just bind the keypress() event handler directly to the selector.

$(".comment").keypress(function(e){
//-^-------- class selector
   if (e.which == 13) 
      alert('works');
});