How to set a value as selected with jQuery autocomplete combobox
We're using the autocomplete combobox for a project and define a select list with options added from a call to an api. I'm adding a first option of 'all' which i'm adding the selected attribute too but the combobox is not picking this up and having 'All' show in the box once it's loaded. I've tried setting the val of the combobox to the 'All' value also, after it's been bound but I'开发者_如何学Pythonve had no joy there. How can I select a default value?
I think you should be able to just set one of the <option>
elements as selected in the usual way:
<option value="x" selected="selected">Stuff</option>
You need to do this before binding the combobox to the <select>
. If you look at the source for the combobox, you'll see this:
var self = this,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "";
var input = this.input = $( "<input>" )
.insertAfter( select )
.val( value )
/* ... */
It looks for the selected children and sets the text input's value to what it finds with an empty string as a fallback. The default "select the first item" that a <select>
element uses is not used here though, you have to explicitly mark an <option>
as selected or the :selected
selector will not, um, select it.
精彩评论