ChosenJs 动态更改默认选项

ChosenJs change default option dynamically

我有一个 select 元素

  <select class="form-control position" name="position">
  <option value="" selected disabled hidden>Pick A Position</option>  
<?php
  $option = 0; 
foreach ($jsonIterator as $key => $val) {
      if(is_array($val)) {
        $option++
 ?>
   <option value="<?  echo $option; ?>"><?  echo $key; ?></option>  
 <?php }}?>   
</select> 

我有 3 个按钮,它们的值分别为 1、2 和 3

<button type='button' value='1' class='btn-primary pull-left apply'>Apply</button> 

我有以下JS

<script>$(document).ready(function () {
    $('.position').chosen();
    $(".apply").click(function () {
        var id = $(this).val();
        $('html,body').animate({ 
          scrollTop: $("#contact").offset().top }, 'slow');
        $.ajax
            ({
                type: "POST",
                url: "contact.php",
                data: id,
                cache: false,
                success: function (html) {
                    $(".positon").val(id).trigger('chosen:updated');
                }
            });
          })
    });

当我点击一个按钮时,ChosenJs 的默认选项没有改变

更新您的选项值,

HTML

<select class="form-control position" name="position">
  <option value="" selected disabled hidden>Pick A Position</option>  
<?php $option = 0; foreach($jsonIterator as $key => $val){ ?>
    <?php if(is_array($val)){ $option++; ?>
   <option value="<?= $option; ?>"><?= $key; ?></option>  
 <?php }}?>   
</select>

并将 select 值传递给 ajax,

jQuery

$(function(){
    $('select[name="position"]').chosen();
    $(".apply").click(function () {
        var id = $(this).val();        
        $('html,body').animate({ scrollTop: $("#contact").offset().top }, 'slow');      
        $.ajax({
            type: "POST",
            url: "contact.php",
            data: { id : id },
            cache: false,
            success: function (html){
                $('select[name="position"]').val(id).trigger("chosen:updated");
            }
        });
    });
});

演示:https://jsfiddle.net/03Lxkoaz/30/