0

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 !

Vince
  • 1,405
  • 2
  • 20
  • 33
  • 1
    `var value = $(this).closest("tr").find(".name-input").val();` you almost got it mate. use closest to find its closest parent. input is just a sibling. you need to do closest parent which is tr then find the specific input try the code about – guradio May 09 '19 at 00:22
  • Brilliant Thank You !! It works ! I had to slightly adjust the `find` to `.find("td .name")` If you were to put this in the answer I could give you an up vote ! Cheers – Vince May 09 '19 at 20:16
  • I will put it an answer – guradio May 09 '19 at 23:43

1 Answers1

1

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.

guradio
  • 15,524
  • 4
  • 36
  • 57