Javascript jQuery 自动完成选择事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26033840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:13:38  来源:igfitidea点击:

jQuery autocomplete selection event

javascriptjqueryjquery-uiautocomplete

提问by Milind

I have created jQuery UI autocomplete which is working very good. But my requirement is that what I display as list should also select same in text box. But it is not selecting For example list like XXX (XYZ) but when I select it only select XXX not XXX (XYZ) what I am missing !!

我创建了 jQuery UI 自动完成功能,效果很好。但我的要求是我显示为列表的内容也应该在文本框中选择相同的内容。但它没有选择例如像 XXX (XYZ) 这样的列表,但是当我选择它时只选择 XXX 而不是 XXX (XYZ) 我缺少什么!

function getDeptStations() {
$("#txDestination").autocomplete({
  source: function (request, response) {
    var term = request.term;
    var Query = "";
    if (lang === "en")
      Query = "City_Name_EN";
    else if (lang === "fr")
      Query = "City_Name_FR";
    if (lang === "de")
      Query = "City_Name_DE";
    if (lang === "ar")
      Query = "City_Name_AR";
    var requestUri = "/_api/lists/getbytitle('Stations')/items?$select=City_Code," + Query + "&$filter=startswith(" + Query + ",'" + term + "')";
    $.ajax({
      url: requestUri,
      type: "GET",
      async: false,
      headers: {
        "ACCEPT": "application/json;odata=verbose"
      }
    }).done(function (data) {
      if (data.d.results) {
        response($.map(eval(data.d.results), function (item) {
          return {
            label: item[Query] + " (" + item.City_Code + ")",
            value: item[Query],
            id: item[Query]
          }
        }));
      }
      else {

      }
    });
  },
  response: function (event, ui) {
    if (!ui.content.length) {
      var noResult = { value: "", label: "No cities matching your request" };
      ui.content.push(noResult);
    }
  },
  select: function (event, ui) {
    $("#txDestination").val(ui.item.label);
            cityID = ui.item.id;
  },
  minLength: 1
});
 }

回答by SSA

Almost there, just return a false from select event.

差不多了,只需从 select 事件中返回一个 false 即可。

select: function (event, ui) {
    $("#txDestination").val(ui.item.label);
            cityID = ui.item.id;
    return false;
  },

or Simply

或者干脆

select: function (event, ui) {        
          alert(ui.item.id);
          return false;
  },

This will guide jquery autocomplete to know that select has set a value.

这将引导 jquery 自动完成知道 select 已经设置了一个值。

Update: This is not in the documentation, I figured out by digging into source code, took me some time. But indeed it deserves to be in the doc or in options.

更新:这不在文档中,我通过深入研究源代码发现,花了我一些时间。但确实它应该出现在文档或选项中。

回答by Onur Topal

in this case you have to options

在这种情况下,您必须选择

  1. the obvious one set value:item[Query] + " (" + item.City_Code + ")"but I am assuming this is not the option.

  2. Handle the selection by yourself first check the api docand you will see event like below. with event.targetyou can access your input with uiyou can access you selected item.

    $( ".selector" ).autocomplete({
        select: function( event, ui ) {}
    });
    
  1. 明显的一组,value:item[Query] + " (" + item.City_Code + ")"但我认为这不是选项。

  2. 自己处理选择首先检查api doc,您将看到如下事件。与event.target您可以访问您输入与ui您可以访问您选择的项目。

    $( ".selector" ).autocomplete({
        select: function( event, ui ) {}
    });
    

回答by Developer

I understand its been answered already. but I hope this will help someone in future and saves so much time and pain.

我知道它已经得到了回答。但我希望这会在将来对某人有所帮助,并节省很多时间和痛苦。

After getting the results in autocomplete you can use below code for keeping the value in the autocomplete textbox field. (you can replace 'CRM.$' with '$' or 'jQuery' depending on your jQuery version)

在自动完成中获得结果后,您可以使用以下代码将值保留在自动完成文本框字段中。 (you can replace 'CRM.$' with '$' or 'jQuery' depending on your jQuery version)

select: function (event, ui) {
                var label = ui.item.label;
                var value = ui.item.value;

                //assigning the value to hidden field for saving the id
                CRM.$( 'input[name=product_select_id]' ).val(value);
                //keeping the selected label in the autocomplete field
                CRM.$('input[id^=custom_78]').val(label);
                return false;
        },

complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone

完整代码如下:这是我为文本框所做的,使其在 CiviCRM 中自动完成。希望它可以帮助某人

CRM.$( 'input[id^=custom_78]' ).autocomplete({
            autoFill: true,
            select: function (event, ui) {
                    var label = ui.item.label;
                    var value = ui.item.value;
                    // Update subject field to add book year and book product
                    var book_year_value = CRM.$('select[id^=custom_77]  option:selected').text().replace('Book Year ','');
                    //book_year_value.replace('Book Year ','');
                    var subject_value = book_year_value + '/' + ui.item.label;
                    CRM.$('#subject').val(subject_value);
                    CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
                    CRM.$('input[id^=custom_78]').val(ui.item.label);
                    return false;
            },
            source: function(request, response) {
                CRM.$.ajax({
                    url: productUrl,
                        data: {
                                        'subCategory' : cj('select[id^=custom_77]').val(),
                                        's': request.term,
                                    },
                    beforeSend: function( xhr ) {
                        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },

                    success: function(result){
                                result = jQuery.parseJSON( result);
                                //console.log(result);
                                response(CRM.$.map(result, function (val,key) {
                                                         //console.log(key);
                                                         //console.log(val);
                                                         return {
                                                                 label: val,
                                                                 value: key
                                                         };
                                                 }));
                    }
                })
                .done(function( data ) {
                    if ( console && console.log ) {
                     // console.log( "Sample of dataas:", data.slice( 0, 100 ) );
                    }
                });
            }
  });

PHP code on how I'm returning data to this jquery ajax call in autocomplete:

关于我如何在自动完成中将数据返回到这个 jquery ajax 调用的 PHP 代码:

/**
 * This class contains all product related functions that are called using AJAX (jQuery)
 */
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
  static function getProductList() {
        $name   = CRM_Utils_Array::value( 's', $_GET );
    $name   = CRM_Utils_Type::escape( $name, 'String' );
    $limit  = '10';

        $strSearch = "description LIKE '%$name%'";

        $subCategory   = CRM_Utils_Array::value( 'subCategory', $_GET );
    $subCategory   = CRM_Utils_Type::escape( $subCategory, 'String' );

        if (!empty($subCategory))
        {
                $strSearch .= " AND sub_category = ".$subCategory;
        }

        $query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
        $resultArray = array();
        $dao = CRM_Core_DAO::executeQuery( $query );
        while ( $dao->fetch( ) ) {
            $resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
        }
        echo json_encode($resultArray);
    CRM_Utils_System::civiExit();
  }
}