-
Notifications
You must be signed in to change notification settings - Fork 26
Setting an Initial Value
Similar to how a <select>
element can have a selected <option>
when the page loads, so to can Marco Polo be set with an initially selected value (or previously selected value in the context of an edit page).
The recommended method for doing this — which properly keeps your HTML separate from your JavaScript — is to set the selected value (string or JSON object) in the data-selected
attribute of your <input>
:
<input type="text" name="userSearch" id="userSearch" data-selected="{ "first_name": "Win", … }">
When Marco Polo is initialized on the <input>
, the data-selected
value is automatically parsed and the onSelect
callback is triggered, just as if the value were selected from the results list.
Important: Be sure to properly encode the string of JSON!
If you're only working with simple strings (as opposed to JSON objects), the standard value
attribute of the <input>
can be set with the selected value. As with the data-selected
attribute described above, it's parsed when Marco Polo is initialized:
<input type="text" name="userSearch" id="userSearch" value="Win Butler">
The initially selected value can also be specified with the selected
option:
$('#userSearch').marcoPolo({
selected: {
first_name: 'James',
last_name: 'Butler',
profile_url: '/users/78749',
…
}
});
The third and final method can be used to set the initial value on page load, but is primarily used to programmatically change the selected value at some point after page load:
$('#userSearch').marcoPolo('select', { first_name: 'James', … });