Search code examples
phpjqueryjquery-traversing

How to select the value of a specific text field when they all have the same class name


I have a table which is generated using a foreach in PHP (Laravel). The table has 3 columns: "Name", "Notes" and "Deactivate". Deactivate is a select with options, "Activate and "Inactive". The "Name" column is made up of a text input field with the class=name. "Deactivate" option has a class of edit_cat.

<tr>
   <td>{{ Form::text("category_name[]",$category->name,['class'=>'name',])}}</td>
   <td>{{ Form::text("notes[]",$category->notes)}}</td>
   <td>{{ Form::select("category_value[]",['active'=>'Active' ,'inactive' => 'Inactive'],$category->status,['class'=>'edit_cat'])}}</td>
</tr> 

When I select an option from column 3,"deactivate", my JQuery needs to also grab the text value of the "category_name" in column one.

I have tried everything I can find in the JQuery API, and here in SO. I have used closest and find, with input:text .name OR, td.name or a dozen other permutations.But I only get undefined back, or an error.

 $(".edit_cat").on("change", function () {
       var value =  $(this).closest(".name-input").val();
       console.log(value);
    });

What am I doing wrong? Many Thanks !


Solution

  • var value = $(this).closest("tr").find("td .name").val();

    You almost got it mate.

    1. Use closest to find its closest parent because input is just a sibling.
    2. You need to do closest parent which is tr then find the specific input.

    closest()

    Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.