问题
I have a form that directors fill out when they add an event to my database. Since the particular type of event is likely to happen more than once, I am trying to make it as easy as possible for them. Using autocomplete, I get the text values to work just fine. Having problems with radio buttons.
Example: there are 3 types of formats available - handicap, scratch, or both. Handicap is value 1, scratch is value 2 and both is value 3. I am able to add the correct value to the table when they first enter their event. How do I set the radio button that corresponds (format_1 for handicap, format_2 for scratch, format_3 for both) using autocomplete?
$('#format').val(ui.item.f);
will return the value from the table if I use text instead of radio button
I tried to make a variable ( i.e. var f = $(".format").val();) which didn't work. What I was thinking about was something similar to setting a variable (f, for example), that would set a radio button (format_f = checked, for instance), but haven't been able to figure out how to mechanize it. Haven't been able to find any direction from my books or on the Internet.
Can someone please point me in the right direction?
回答1:
You need to inject this into the select
function of your autocomplete. It's possible your instantiation of autocomplete does not have one, as it's not necessary for default behaviour.
Obviously you need to have the mapping of the autocomplete options and formats available, and you can have this sent back by whatever generates the autocomplete data. (It's not clear in your example whether your autocomplete is AJAX or local, but it doesn't matter.)
Ultimately you want your autocomplete to have entries like this:
[ { "id":"foo", "value":"bar", "f":"1" },
{ "id":"baz", "value":"quux", "f":"2" } ]
Then your select function at the end of your autocomplete will look like:
select: function(event, ui) {
if (ui.item) {
$('#format').val(ui.item.f);
}
}
I wrote a complete example in a similar question a few days back.
来源:https://stackoverflow.com/questions/7522930/setting-a-radio-button-based-on-jquery-autocomplete-value