Ad

Get The Value Of A Foreach Loop From Laravel Balde And Pass It To Javascript Function

- 1 answer

i have this For-each loop in my Laravel blade engine and i'm trying to pass the id and name to my Javascript function using button click event and log it to console,

Logic: attached image as example (1.) once button ADD is click the Student from Point A will go to Point B (2.) once button DELETE click the student from Point A will be remove from Point B and back to Point A enter image description here

Now what i have tried so far is logging the student name and id to the console using console.log, but problem is only the ID of the First student will come out. Example if i Click Student 3 = the id is 1 it is not getting the real ID of the student. how do i approach this and what is the best suggestion to achieve my goal

CODES

@foreach($students as $std)
        <input id="myInput"  type="button" value="{{$std->name}}" onclick="addRow()">
        @endforeach

function addRow() {
    var inputVal = document.getElementById("myInput").value;
    console.log(inputVal);  
}
Ad

Answer

Add data attributes to you input field and get them on onclick(). Here is data attribute documentation.

Code using Jquery

@foreach($students as $std)
    <input id="myInput"  type="button" data-name="{{$std->name}}" data-id="{{$std->id}}" value="{{$std->name}}" onclick="addRow(this)">
@endforeach

function addRow(ele) 
{
    var name= $(ele).attr('data-name');
    var id= $(ele).attr('data-id');
    console.log(name);  
    console.log(id);  
}
Ad
source: stackoverflow.com
Ad