Search code examples
jqueryjquery-select2onchange

Interaction between 2 selected select2


I received data from MySql into both select2.

<div class="input-group input-group-sm mb-3 kod_gecis">  
  <select name="p_code" id="p_code" class="form-control kod_ara">
<?php
foreach ($result4 as $row3) {
  echo '<option data-pname="' . $row3['ProductName'] . '" value="' . $row3['ProductCode'] . '">'
    . $row3['ProductCode']
    . '</option>';
}
?>
  </select>
</div>
<div class="input-group input-group-sm mb-3 border border-warning gecis">
  <select name="p_name" id="p_name" class="form-control urun_ara">
<?php
foreach ($result2 as $row) {
  echo '<option data-pcode="' . $row['ProductCode'] . '" data-inbox="' . $row['PiecesInBox'] . '" data-price="' . $row['Price'] . '" name="' . $row['ProductName'] . '" value="' . $row['ProductName'] . '">'
    . $row['ProductName']
    . '</option>';
}
?>
  </select>
</div>

When I'm trying to select p_name, its going to change p_code select2 very well.
But the problem is for secondary one. I would be change to p_name while according to selected value of p_code.
This could be work like this:
Receives value from p_code selected value of data-pname, after then it should be equals to p_name value and search it.
Because some inputs works according to p_name change function.
Those both codes are working under document ready function.

$('#p_name').change(function() {
  var pcode = $('#p_name option:selected').data('pcode');
  $('#p_code').val(pcode).trigger("change");
});
$('#p_code').change(function() {
  var pname = $('#p_code option:selected').data('pname');
  $('#p_name').val(pname).trigger("change"); // it's not working
  $('#p_name').select2('');
});

Solution

  • I solved my problem. And im going to share for who needs to use interaction between 2 selected select2.

    You should do for first function with

    change function

    like this:

    $('#p_name').change(function(){
        var pcode = $('#p_name option:selected').data('pcode');
        $('#p_code').val(pcode).trigger("change");
        });
    

    For secondary one, you should use to

    'select2:select'

    function in order to get your first select2 selected value from data according to your data attribute and instantly select your secondary selected value.

    The working code is below (for the secondary select2):

    $('#p_code').on('select2:select', function () {
        var data = $('#p_code option:selected').data('pname');
    $('#p_name').val(data).trigger('change');
    });