jQuery自动完成选择事件

时间:2014-09-25 08:24:57

标签: javascript jquery jquery-ui autocomplete

我创建了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
});
 }

3 个答案:

答案 0 :(得分:36)

几乎就在那里,只需从select事件中返回一个false。

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

或简单

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

这将指导jquery自动完成知道select已设置值。

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

答案 1 :(得分:1)

我知道它已经得到了解答。但我希望这将有助于将来的某些人,并节省大量的时间和痛苦。

在自动填充中获得结果后,您可以使用以下代码将值保留在自动填充文本框字段中。 (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;
        },

完整代码如下:这是我为文本框做的,使其在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 ) );
                    }
                });
            }
  });

关于我如何在自动完成中将数据返回到此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();
  }
}

答案 2 :(得分:0)

在这种情况下你必须选择

  1. 显而易见的一组value:item[Query] + " (" + item.City_Code + ")",但我认为这不是选项。

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

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