Плагин JQuery selected - отправка введенного пользователем ввода в вызов Ajax - PullRequest
0 голосов
/ 30 апреля 2019

Я пытаюсь заполнить выпадающий список с помощью плагина Chosen для множественного выбора.

Я добавил скрипку

http://jsfiddle.net/san1234/ymnj12xk/

Мое намерение состоит в том, чтобы заполнить тег «options» в теге «select», основываясь на данных JSON, полученных путем отправки набранного пользователем письма посредством вызова Ajax.

Для этого мне нужно знать, как сделать ajax-вызов onkeyup, т.е. если пользователь набрал «Am», я хочу отправить этот ввод на Ajax-вызов и получить ответ JSON, что-то вроде [«America», « Амстердам "]

Я новичок в этом и не могу найти способ извлечь введенный пользователем ввод в поле 'select', чтобы фактически отправить его как запрос в Ajax-вызове.

Я пытался сделать это, но метод автозаполнения в файле JS не работает Как мне это сделать? любезно помогите!

Файл JS

$(".chosen-select").chosen();

$(".chosen-select-deselect").chosen({
  allow_single_deselect: true
});
$('.chosen-choices input').autocomplete({
  source: function(request, response) {
    $.ajax({

      url: "/someURL/" + request.term + "/",
      dataType: "json",
      beforeSend: function() {
        $('ul.chosen-results').empty();
      },
      success: function(data) {
        alert("Success!");
        response($.map(data, function(item) {

          $('ul.chosen-results').append('<li class="active-result">' + item.name + '</li>');
        }));
      }
    });
  }
});
<link href="http://harvesthq.github.io/chosen/chosen.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://harvesthq.github.io/chosen/chosen.jquery.js"></script>
<select class="chosen chosen-select" multiple="" data-placeholder="Choose a Country" style="width:200px">
    <option value="America">America</option>
     <option value="Amsterdam">Amsterdam</option>
      <option value="Australia">Australia</option>
    <option value="Dallas">Dallas</option>
    <option value="GHI">hij</option>
</select>

1 Ответ

0 голосов
/ 02 мая 2019

Я не знаю, используете ли вы PHP в своем бэк-энде или другом языке программирования, но вот мое решение с использованием php и javascript:

Сначала ваш javaScript:

//initialization of chosen select
$(".chosen-select").chosen({
  search_contains: true // an option to search between words
});
$(".chosen-select-deselect").chosen({
  allow_single_deselect: true
});

//ajax function to search a new value to the dropdown list
function _ajaxSearch (param){
  return $.ajax({
    url: "request.php",
    type: "POST",
    dataType: "json",
    data: {param:param}
  })
}
//key event to call our ajax call
$(".chosen-choices input").on('keyup',function(){
  var  param = $('.chosen-choices input').val();// get the pressed key
  _ajaxSearch(param)
  .done(function(response){
    var exists; // variable that returns a true if the value already exists in our dropdown list
    $.each(response,function(index, el) { //loop to check if the value exists inside the list
      $('#mySelect option').each(function(){
        if (this.value == el.key) {
          exists = true;
        }
      });
      if (!exists) {// if the value does not exists, added it to the list
        $("#mySelect").append("<option value="+el.key+">"+el.value+"</option>");
        var ChosenInputValue = $('.chosen-choices input').val();//get the current value of the search
        $("#mySelect").trigger("chosen:updated");//update the list
        $('.chosen-choices input').val(ChosenInputValue);//since the update method reset the input fill the input with the value already typed
      }
    });
  })
})

ваш php файл:

if (isset($_POST["param"])) {// check is the param is set
$param = $_POST["param"]; // get the value of the param
$array  = array('JKL' => 'jkl' , 'MNO'=>'mno', 'PQR'=>'pqr','STU'=>'stu','VWX'=>'vwx','YZ'=>'yz' );//array of values
$matches = array();//array of matches
    foreach($array as $key=>$value){//loop to check the values
        //check for match.
        if(strpos($value, $param) !== false){
            //add to matches array.
            $matches[]= array ("key"=> $key,"value"=>$value);
        }
    }
//send the response using json format
echo json_encode($matches);
}

Надеюсь, это поможет

...