automatically fill input when select dropdown based on their rows input

  ajax, javascript, jquery, php

I’m successful retrieving data from MySql database into a dynamically inputs using PHP & Ajax. but i have problem where when I select value for another input element, it also change my first row input element. how do i solve this problem ?

this is the visualize of how my code work.

supposed i want to make like this. but, it change for 1st and 2nd row of the inputs

here is my ajax

 <script>

$(document).on('change', '[name="accessoriesModel[]"]', function(){ /* WHEN AN ALBUM HAS BEEN SELECTED */

  var accessories_id = $(this).val(); 

  $.ajax({ 
    type: "POST", 
    url: "getcode.php", 
    data: {"accessories_id": accessories_id}, 
    dataType: "json", 
    success: function(result){ 
      

      $('[name="accessories_id[]"]').val(accessories_id);
      $('[name="accessories_code[]"]').val(result.accessories_code);
      $('[name="accessories_name[]"]').val(result.accessories_name);
      
  
    } 
  }); 

});
    </script>

this is my php code

<form class="form-inline" id="frm-add-data" action="javascript:void(0)">
      
            <div class="model">
                <select id="accessoriesModel" name="accessoriesModel[]"> <option value=""> Select Accessories Code </option>
<?php include "dbconnect.php";  // Using database connection file here
                    $records = mysqli_query($db, "SELECT accessories_code, accessories_name, accessories_id  From accessories_list ORDER BY accessorieslistlasmodify_at DESC");  // Use select query here 

                    while($data = mysqli_fetch_array($records))
                     {
                         
                     echo "<option value='". $data['accessories_id'] ."'>" .$data['accessories_code']. "      -      " . $data['accessories_name']."</option>";  // displaying data in option menu
                     }  
  ?>   
</select>

<input type="text" name="accessories_id[]" id="accessories_id" class="">
<input type="text" id="code" name="accessories_code[]" placeholder="Accessories Code" class="form-control">
<input type="text" id="accessories_name" name="accessories_name[]" placeholder="Accessories Name" class="form-control">
<input type="text" id="accQuan" name="accessories_quantity[]" placeholder="Accessories Quantity"  class="form-control">

<?php if (isset($_SESSION["username"])) ?>
<input type="hidden" name="jobregistercreated_by" id="jobregistercreated_by" value="<?php echo $_SESSION["username"] ?>" readonly>
<input type="hidden" name="jobregisterlastmodify_by" id="jobregisterlastmodify_by" value="<?php echo $_SESSION["username"] ?>" readonly>

<a href="javascript:void(0);" class="add_button" title="Add field">+</a>
            
            </div>
        </div>
</form>

btw, i use multiple input add wrapper.
your help is much appreciated.

Source: Ask PHP

LEAVE A COMMENT