我已嵌入此jQuery自动完成下拉列表:https://jqueryui.com/autocomplete/#combobox
我稍微更改了代码以获得占位符。 这是我的代码:
<select id="provider" name="provider" required="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<script>
$( function() {
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" ).appendTo( this.wrapper ).val( value ).attr( "title", "" ).attr( "placeholder", "My Placeholder" ).addClass("form-control input-md")
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
classes: {
"ui-tooltip": "ui-state-highlight"
}
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input.val( "" ).attr( "title", "Error" ).tooltip( "open" );this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
$( "#provider" ).combobox();
} );
</script>
问题是,我在加载页面后没有直接获得占位符 - 它将显示我的下拉列表的第一个元素 - 在这种情况下是值&#34; 1&#34;。 如果我从输入字段中删除文本手册,将显示占位符。有人有点想法吗? :)