skip to Main Content

I would like to know how to check the checkbox that is associated with the student found by my jQuery search function.To understand here is my "Ajax" request. Currently it displays the result of my search in a html ‘span’ but I just want to check the checkbox associated with the search.

This is my jQuery code where I do my request :

const { post } = require("jquery");

const form = document.getElementById('search-codebar-form');

form.addEventListener('submit', function (e) {
    e.preventDefault();

    const token = document.querySelector('meta[name="csrf-token"]').content;
    const url = this.getAttribute('action');
    const q = document.getElementById('q').value;
   

    fetch(url, {
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': token
        },
        method: 'post',
        body: JSON.stringify({
          q: q
        })
    }).then(response =>  {
        response.json().then (data => {

            // const newid = "student-${{id}}";

             document.getElementById(newid).checked = true;
            var data = {};
            data = "{{ $student->id }}";
    $("#student-.data").prop("checked", true); // And here I'm trying to take the id of the checkbox
 and check it.Watch out because the id change with the result because it is "student-{{ $student->id }}"
----------------------------------------------------------------
           // const etudiant = document.getElementById('etudiant');
            etudiant.innerHTML = '';


            Object.entries(data)[0][1].forEach(element =>{
               etudiant.innerHTML = `<span>${element.first_name}</span>`// At the moment
 I have this .So this empty my "div" and show the name of the result.
              
            });
        })
    }).catch(error =>{
        console.log(error)
    })

});

And this is my form where this input is in my .blade
The tag ” is much higher in my code but I just wanna show you the most important.

<div id="etudiant">         
                  @foreach ($students as $student)
                   <tbody class="bg-white divide-y divide-gray-200">
                      <tr>
                        <td class="px-6 py-4 whitespace-nowrap">                
                              <div class="text-sm font-medium text-gray-900">
                      {{$student->last_name}}
                          </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">
                          {{$student->first_name}}
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">
                          {{$student->uuid}}
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">      
                             <input class="form-check-input" type="checkbox"  name="students[]" type="checkbox" value="{{ $student->id }}" id="student-{{ $student->id }}" />    
                            </div>
                        </td>
                      </tr>
                    </tbody> 
                   
                    @endforeach 
                       </div>

If you want more this is my Laravel controller associate to the request.

public function search_codebar(request $request): JsonResponse
    {

      $q = $request->input('q');

      $students = Student::where('uuid', 'like' ,$q )->get();

      return response()->json([
        "students" => $students]);
    }
    public function list_appel($id){
    return view('list_appel', ["appels" => Appel::all()]);
    
    }

So "q" in my jQuery code in define here to search the "uuid" of the student.
I hope you can understand what is my problem.
Thanks a lot !

https://i.stack.imgur.com/1eqcK.png

2

Answers


  1. Chosen as BEST ANSWER

    I found the answer :

    .then((response) => response.json())
            .then((data)=>{
    const students = data.students
    students.forEach((student) => {
                    $(`#student-${student.id}`).prop("checked", true)
                
                })
    
            })  
            .catch((error) => {
                console.log(error);
            });
        });
    

    My data was an object and not an array ! So I had to use .then((data)=>{ const students = data.students


  2. data = "{{ $student->id }}";

    does not seem to belong there. It is not part of the JavaScript and will be filled in when the page loads. That is unlikely what you want

    IF your server returns JSON that contains an array of students and has the uuid, then you can do something like

     }).then(response => response.json())
      .then (data => {
        data.forEach(student => $(`#student-${student.id}`).prop("checked", true))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search