ChosenJs动态更改默认选项

时间:2018-04-19 07:57:11

标签: javascript php jquery jquery-chosen

我有一个选择元素

  <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的默认选项不会改变

1 个答案:

答案 0 :(得分:1)

更新您的选项值,

<强> 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>

并将选择值传递给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/