skip to Main Content

I have below table :

.
.
.

<td >
    <input type="text"   class="car_color"     >
    <input type="hidden" class="number_car" name="my_timelist[times][]" value="0">
</td> 
 
<td >
    <input type="text"   class="car_color"     >
    <input type="hidden" class="number_car" name="my_timelist[times][]" value="0">
</td> 

<td >
    <input type="text"   class="car_color"     >
    <input type="hidden" class="number_car" name="my_timelist[times][]" value="0">
 </td> 
 
.
.
.

I want set value on input with class name class="number_car" by jquery with below code, But this effect on all inputs(have the class name). But I want effect value just on same td.

` $(‘.car_color’).change(function(){

    let datetime    = $(this).val();

   $('.number_car').val( 123456);
}); 

`
How can I fix?

2

Answers


  1. You could use .closest() to traverse up to the same cell containing the other desired input, then .find() it there. Another alternative is $this.siblings(".number_car") if the elements are siblings.

    $(".car_color").change(function () {
      let $this = $(this);
      let datetime = $this.val();
      $this.closest("td").find(".number_car").val(123456);
    });
    .number_car {
      opacity: 0.5;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <table>
      <tbody>
       <tr>
        <td>
         <input class="car_color" type="text">
         <input class="number_car" name="my_timelist[times][]" value="0" readonly>
        </td>
        <td>
         <input class="car_color" type="text">
         <input class="number_car" name="my_timelist[times][]" value="0" readonly>
        </td>
        <td>
         <input class="car_color" type="text">
         <input class="number_car" name="my_timelist[times][]" value="0" readonly>
        </td>
       </tr>
      </tbody>
     </table>
    Login or Signup to reply.
  2. There are many ways to get this and in your situation next() would be a good fit.

    $(".car_color").change(function () {
      let datetime = $(this).val();
      let hiddenInput = $(this).next(".number_car");
      hiddenInput.val(123456);
    });
    

    You can look at the demo here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search