在jQuery组合框上选择一次下拉项后触发事件

时间:2013-10-12 18:47:24

标签: javascript jquery html forms jquery-ui

我正在使用jQuery UI库中的自动完成组合框创建一些也接受下拉菜单的文本字段 - 基本上是混合文本/下拉输入。我定制了它,因此它也接受自由文本输入,而不仅仅是下拉数组中的项目。

当用户从下拉列表中选择一个项目时,我想触发一个根据输入填充表单其余部分的函数。当用户手动输入值时,我不希望触发此功能。我不确定如何将事件特别绑定到用户从下拉列表中选择项目。

这是一个小提琴:http://jsfiddle.net/AhDHk/

HTML:

    <input type="text" name="realtor-name" id="lp-realtor-name" value="" class="text ui-widget-content ui-corner-all" />

JS:

// adds the dropdown, dropArray is the list of items for the dropdown, id is the ID of the html input. 

function textDropdown(dropArray, id) {
var $input = $(id).autocomplete({
    source: dropArray, // this is an array fetched with AJAX of all the items for the dropdown
    minLength: 0
}).addClass("ui-widget ui-widget-content ui-corner-left");


$("<button type='button'>&nbsp;</button>")                     
    .attr("tabIndex", -1)                     
    .attr("title", "Show All Items")                     
    .insertAfter($input)                     
    .button({                         
        icons: {                             
            primary: "ui-icon-triangle-1-s"                         
        },                         
        text: false                     
    })                     
    .removeClass("ui-corner-all")                     
    .addClass("ui-corner-right ui-button-icon lp-drop-button")   
    .click(function() {                         
        // close if already visible                         
        if ($input.autocomplete("widget").is(":visible")) { 
             $input.autocomplete( "close" );
             return;                         
        }                                              
        $(this).blur();                                                 
        $input.autocomplete("search", "" );                         
        $input.focus();                     
    });

$("form").submit(function(e) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
    alert($(this).serialize());
});
}

2 个答案:

答案 0 :(得分:3)

以下是如何处理它:

var $input = $(id).autocomplete({
    source: dropArray, // this is an array fetched with AJAX of all the items for the dropdown
    minLength: 0,
    select: function(event, ui) { alert('test');}
}).addClass("ui-widget ui-widget-content ui-corner-left");

可能重复:jQuery UI Autocompleteselect

答案 1 :(得分:1)

选择事件here

function textDropdown(dropArray, id) {
var $input = $(id).autocomplete({
    source: dropArray, // this is an array fetched with AJAX of all the items for the dropdown
    minLength: 0,
    select:function(a,b){
          alert(b.item.value + 'selected');
    }
}).addClass("ui-widget ui-widget-content ui-corner-left");
相关问题