Define a JS variable different from PHP foreach loop


I have very annoying problem, I need to display MySQL queries by using a PHP foreach loop but because of this when i try to set a javascript value for each of the items that are looped through it only selects either the first or last value it ignores the rest.

Here's what i've tried so far:

I have given an input a class and given it a value as well, this is within the for-each loop.

<input class="classs" value="{{ $item->id }}"/>

Next i have tried to access this from a js function, which is outside of the for-each loop.

    function addSubTaskToDatabase(){
    var itemId = $('.class').val();


Problem is all this does is alert the last value in the for-each loop with that class, its the same for name and for id also.

Anyone know the fix..? all help is appreciated.

var itemId = $('.class').val();

is going to select all elements on the page with that class.

You probably want a click function on the elements, and use this to access the currently-clicked item:

$('.class').click(function() {
    var itemId = $(this).val();