选择<optgroup>多输入1选择

时间:2017-11-29 16:47:17

标签: php jquery laravel

我有2个foreach在1选择与不同的组。如果从2nd optgroup中选择值,我想将输入从serviceid更改为domain id。

<select class="form-control select2" id="serviceid" name="serviceid" required>
   <option disabled selected value> -- Select -- </option>
   <optgroup label="Products">
       @foreach($services['product'] as $service)
           <option value="{{ $service['id'] }}">{{ $service['name'] }}</option>
       @endforeach  
   </optgroup>

   <optgroup label="Domains">
       @foreach($domains['domain'] as $domain)
           <option value="{{ $domain['id'] }}">{{ $domain['domainname'] }}</option>
       @endforeach  
   </optgroup>

</select>

现在输出始终带有"serviceid" => "2" 如果从标签Domains 2nd array中选择了某些东西,我想要"domainid" => "1"

1 个答案:

答案 0 :(得分:1)

您可以使用隐藏输入来处理这两种情况,例如下面显示的代码段,您可以使用服务器端代码中的非空代码进行过滤。

希望这有帮助。

&#13;
&#13;
$('#serviceid').select2();

$('#serviceid').on('change', function() {
  var label = $('#serviceid :selected').parent().attr('label');

  if (label == "Domains") {
    $('.domainid').val($(this).val());
    $('.serviceid').val("");
  } else if (label == "Products") {
    $('.serviceid').val($(this).val());
    $('.domainid').val("");
  }

  console.log('domainid=' + $('.domainid').val());
  console.log('serviceid=' + $('.serviceid').val());
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>

<input type="hidden" name="domainid" class="domainid" />
<input type="hidden" name="serviceid" class="serviceid" />

<select class="form-control select2" id="serviceid" style="width: 300px">
  <option disabled selected value> -- Select -- </option>
  <optgroup label="Products">
    <option value="FEB">February</option>
    <option value="MAR">March</option>
    <option value="APR">April</option>
    <option value="MAY">May</option>
    <option value="JUN">June</option>
    <option value="JUL">July</option>
  </optgroup>

  <optgroup label="Domains">
    <option value="AUG">August</option>
    <option value="SEP">September</option>
    <option value="OCT">October</option>
    <option value="NOV">November</option>
    <option value="DEC">December</option>
  </optgroup>
</select>
&#13;
&#13;
&#13;