문제

나는 비교적 간단한 방법으로 jQuery의 자동 완성을 사용하고 있습니다.

$(document).ready(function() {
  var data = [ {text: "Choice 1"}, 
               {text: "Choice 2"}, 
               {text: "Choice 3"} ]

$("#example").autocomplete(data, {
  matchContains: true,
  minChars: 0,
  formatItem: function(item) 
    { return item.text; }
    }
  );
  });

자동 완성에 사용 가능한 모든 선택 사항을 표시하는 onclick 이벤트(예: 버튼 또는 링크)를 어떻게 추가합니까?기본적으로 저는 자동 완성과 선택/드롭다운 요소를 혼합한 요소를 만들고 싶습니다.

감사해요!

도움이 되었습니까?

해결책

문서에서 그렇게하는 명백한 방법을 볼 수는 없지만 AutoComplete 활성화 된 텍스트 상자에서 초점 (또는 클릭) 이벤트를 트리거하려고합니다.

$('#myButton').click(function() {
   $('#autocomplete').trigger("focus"); //or "click", at least one should work
});

다른 팁

이 이벤트를 트리거하여 모든 옵션을 표시할 수 있습니다.

$("#example").autocomplete( "search", "" );

또는 아래 링크의 예를 참조하세요.정확히 당신이하고 싶은 일인 것 같습니다.

http://jqueryui.com/demos/autocomplete/#combobox

편집하다 (@cnanney에서)

메모:minLength를 설정해야 합니다.모든 요소를 ​​반환하려면 빈 검색 문자열에 대한 자동 완성에서 0을 입력하세요.

나는 이것이 가장 잘 작동한다는 것을 알았습니다

var data = [
    { label: "Choice 1", value: "choice_1" },
    { label: "Choice 2", value: "choice_2" },
    { label: "Choice 3", value: "choice_3" }
];

$("#example")
.autocomplete({
    source: data,
    minLength: 0
})
.focus(function() {
    $(this).autocomplete('search', $(this).val())
});

레이블을 검색하고 값을 요소 $ (#example)에 배치합니다.

모든 항목을 표시하려면 Combobox 동작을 시뮬레이션하려면 먼저 Minlength 옵션을 0으로 설정했는지 확인해야합니다 (기본값은 1). 그런 다음 클릭 이벤트를 바인딩하여 빈 문자열로 검색을 수행 할 수 있습니다.

$('inputSelector').autocomplete({ minLength: 0 });
$('inputSelector').click(function() { $(this).autocomplete("search", ""); });

솔루션 : 포커스 이벤트에 jQuery UI 자동 완성 목록을 표시합니다

그것을 두 번 이상 작동시키는 솔루션

<script type="text/javascript">
$(function() {
    $('#id').autocomplete({
        source: ["ActionScript",
                    /* ... */
                ],
        minLength: 0
    }).focus(function(){     
        //Use the below line instead of triggering keydown
        $(this).data("autocomplete").search($(this).val());
    });
});

이 시도:

    $('#autocomplete').focus(function(){
        $(this).val('');
        $(this).keydown();
    }); 

그리고 미세한 길이 로 설정 0

매번 작동합니다 :)

 $j(".auto_complete").focus(function() { $j(this).keydown(); })

~ 해야 하다 세트 minLength 에게 이 일을하기 위해! 다음은 작동 예입니다.

$( "#dropdownlist" ).autocomplete({
      source: availableTags,
      minLength: 0 
    }).focus(function() {
      $(this).autocomplete('search', $(this).val())
    });
});

이것이 나를 위해 일하는 유일한 것입니다. 목록은 매번 표시하고 선택시 닫힙니다.

$("#example")
.autocomplete(...)
.focus(function()
{
  var self = this;

  window.setTimeout(function()
  {
    if (self.value.length == 0)
      $(self).autocomplete('search', '');
  });
})

당신은 이것을 사용할 수 있습니다 :

$("#example").autocomplete( "search",  $("#input").val() );

이것은 모든 옵션을 보여줍니다. "%" (아래 참조)

중요한 것은 아래 예제에서와 같이 이전 #example 선언 아래에 배치해야한다는 것입니다. 이것은 나를 알아내는 데 시간이 걸렸다.

$( "#example" ).autocomplete({
            source: "countries.php",
            minLength: 1,
            selectFirst: true
});

$("#example").autocomplete( "search", "%" );

이것이 누군가를 도울 수 있기를 바랍니다.

$('#id')
        .autocomplete({
            source: hints_array,
            minLength: 0, //how many chars to start search for
            position: { my: "left bottom", at: "left top", collision: "flip" } // so that it automatically flips the autocomplete above the input if at the bottom
            })
        .focus(function() {
        $(this).autocomplete('search', $(this).val()) //auto trigger the search with whatever's in the box
        })
<input type="text" name="q" id="q" placeholder="Selecciona..."/>


<script type="text/javascript">
//Mostrar el autocompletado con el evento focus
//Duda o comentario: http://WilzonMB.com
$(function () {
    var availableTags = [
        "MongoDB",
        "ExpressJS",
        "Angular",
        "NodeJS",
        "JavaScript",                
        "jQuery",
        "jQuery UI",
        "PHP",
        "Zend Framework",
        "JSON",
        "MySQL",
        "PostgreSQL",
        "SQL Server",
        "Oracle",
        "Informix",
        "Java",
        "Visual basic",
        "Yii",
        "Technology",
        "WilzonMB.com"
    ];
    $("#q").autocomplete({
        source: availableTags,
        minLength: 0
    }).focus(function(){            
       $(this).autocomplete('search', $(this).val())
     });
});
</script>

http://jsfiddle.net/wimarbueno/6zz8euqe/

속성 Minchars : 0 이후에 2 번의 클릭을 트리거하여 이것을 해결했습니다. (입력을 1 번 클릭 한 후 자동 완성 쇼) 내 코드

<input type='text' onfocus='setAutocomplete(this)'>

function setAutocomplete(el){
    $(el).unbind().autocomplete("./index.php", {autoFill:false, minChars:0, matchContains:true, max:20});
    $(el).trigger("click");$(el).trigger("click");
}

나는 완전한 것처럼 보이는 모든 대답을 보았다.

커서가 텍스트 필드에 있거나 일치하는 레이블을 클릭 할 때 목록을 얻으려면 다음을 수행 할 수 있습니다.

//YourDataArray = ["foo","bar"];
$( "#YourID" ).autocomplete({
            source: YourDataArray 
        }).click(function() { $(this).autocomplete("search", " "); });

이것은 Firefox, 즉 크롬에서 잘 작동합니다 ...

$("#searchPkgKeyWord").autocomplete("searchURL",
        {
            width: 298,
            max: 1000,
            selectFirst: false
        }).result(function (event, row, formatted) {
            callback(row[1]);
        }).focus(function(){
            $(this).click(); //once the input focus, all the research will show
        });

나는 그것을 얻을 수 없었다 $("#example").autocomplete( "search", "" ); 내 소스에 존재하는 문자로 검색을 변경한 후에만 작동합니다.그래서 나는 예를 들어 다음을 사용했습니다. $("#example").autocomplete( "search", "a" );.

더 나은 옵션은 $ ( "#idname")를 넣는 것 같아요. 텍스트 상자의 onclick 매개 변수로. Select에서는 jQuery가 초점을 맞추기 때문에 해결 방법이 될 수 있습니다. 그것이 허용되는 솔루션이어야하는지 모르겠습니다.

최근 에이 작업을 수행해야했고 몇 가지 다른 순열 (Onfocus 사용, 텍스트 상자 등을 사용하여)을 시도한 후 마침내이 문제를 해결했습니다.

 <input id="autocomplete" name="autocomplete" type="text" 
 value="Choose Document">

 <p>
 <button type="submit" value="Submit" name="submit" id="submit" >
  Submit
 </button>
 </p>

<script type="text/javascript">

$("#autocomplete").autocomplete(
{
source: '@Url.Content("~/Document/DocumentTypeAutoComplete/")' //<--ddl source
, minLength: 0 // <-- This is necessary to get the search going on blank input
, delay: 0
, select: function (event, ui) 
  {
  if (ui.item) {
     $("#autocomplete").val(ui.item.value);//<-- Place selection in the textbox
          $("docForm").submit(); 
          loadDocTypeCreatePartial(ui.item);
          $("#submit").focus(); //This stops the drop down list from reopening 
                                // after an item in the select box is chosen
                                // You can place the focus anywhere you'd like,
                                // I just chose my *submit* button
                }
   }
  }).focus(function () {
    // following line will autoselect textbox text
    // making it easier for the user to overwrite whats in the 
    // textbox
    $(this).select();

    //The below line triggers the search function on an empty string
    $(this).data("autocomplete").search('');
   });
 </script>

이것은 초점에 대한 자동 완성 DDL 목록을 열어줍니다 (위의 입력 상자에 기본 텍스트가 있더라도 위의 것과 같이).

또한 텍스트 상자의 텍스트를 자동으로 선택하여 사용자가 텍스트를 지우지 않도록합니다.

자동 완성 목록에서 항목이 선택되면 해당 항목을 자동 완성 입력 상자에 넣고 초점을 다른 컨트롤로 이동합니다 (따라서 자동 완성이 재개되지 않도록합니다).

나는 동적 ajax 호출을 아주 좋은 것에 추가하여 교체 할 계획입니다. 선택 The Lists를 선택하십시오 녹는 얼음 기회가 생길 때 업그레이드하십시오.

나는이 방법을 사용했다 :

$("#autocomplete").autocomplete({
                source: YourDataArray,
                minLength: 0,
                delay: 0
            });

그 다음에

OnClientClick="Suggest(this); return false;"/>

 function Suggest(control) {
                var acControl = $("#" + control.id).siblings(".ui-autocomplete-input");
                var val = acControl.val();
                acControl.focus();
                acControl.autocomplete("search");

매개 변수없이 검색 기능을 사용할 수도 있습니다.

jQuery("#id").autocomplete("search", "");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top