user982124
user982124

Reputation: 4610

jQuery UI Auto Complete and HTML Form with Select Menu

I have an HTML form which I'm using the jQuery UI Auto Complete plugin with and it's working well. It allows users to start typing and select from a list of pre-defined activities.

I've further extended this so that it also populates the matching "risk type" associated with the activity which is in the next field which uses a select menu. You can see an example of this here:

http://jsfiddle.net/fmdataweb/pCZYd/

If you type "football" and select one of the options and then press the TAB key it will insert either low, moderate or high into the next field where the select menu is.

Here's the Javascript that handles this:

$(function() {


        $( "#lastYearSelect1" )
            .autocomplete({
                source: availableTags })
            .blur(setDropDown);
    });

if(!Array.prototype.indexOf) {
      Array.prototype.indexOf = function(needle) {
          var i;
          for(i = 0; i < this.length; i++) {
              if(this[i] === needle) {
                  return i;
              }
          }
          return -1;
      };
    }

    var risks = [{
    name: 'low',
    activities: ['10 pin bowling', 'active play', 'activities and games', 'aerobics', 'aquaerobics', 'archery', 'athletics', 'backyard play', 'badminton', 'ball games', 'ball play', 'ballet', 'ballet dancing', 'ballroom dancing', 'beach', 'body surfing', 'bodysurfing', 'boogie boarding', 'bowling', 'bushwalk', 'bushwalking', 'canoeing', 'circuit training', 'contemporary dancing', 'croquet', 'cross country running', 'cross country training', 'dance', 'dance practice', 'dance training', 'dancing', 'dancing lesson', 'discus', 'discus throwing', 'fishing', 'folk dancing', 'frisbee', 'golf', 'golf driving range', 'gym', 'gym - cardio', 'gym - weights and cardio', 'gym - weights/aerobics', 'gym session', 'gym workout', 'gym/weights', 'handball', 'hiking', 'hip hop dancing', 'hip-hop', 'indoor bowling', 'irish dancing', 'javelin', 'jazz', 'jogging', 'kayaking', 'kicking football', 'lawn bowling', 'lifesaving', 'light play ', 'little athletics', 'mini putt putt golf', 'modern dancing', 'nippers', 'pilates', 'ping pong', 'play computer games', 'play wii games', 'play with balls', 'playing', 'playing around', 'playing golf', 'playing pool', 'playing snooker', 'playing with friends', 'playing with toys', 'playstation', 'playstation games', 'pool', 'power walking', 'putt putt golf', 'rowing', 'running', 'scuba diving', 'shot put', 'skipping', 'snooker', 'snorkelling', 'sprinting', 'squad swimming', 'swim training', 'swimming', 'swimming laps', 'swimming lesson', 'swimming training', 'table tennis', 'tai chi', 'tap dancing', 'ten pin bowling', 'throwing', 'throwing javelin', 'throwing shot put', 'tramping', 'treadmill', 'treadmill running', 'walking', 'walking dog', 'weights', 'wii active games', 'wii games', 'wii sport', 'yoga']},
    {
    name: 'moderate',
    activities: ['20/20 cricket', 'abseiling', 'acrobatic gymnastics', 'acrobatics', 'acrobatics class', 'artistic gymnastics', 'austag', 'backyard cricket', 'baseball', 'basketball', 'basketball practice', 'basketball training', 'beach volleyball', 'bicycle', 'bicycling', 'bike ', 'bike ride', 'bike riding', 'bikeriding', 'BMX', 'BMX bike', 'board surfing', 'boarding', 'chasings', 'cheerleading', 'chopping wood', 'climbing', 'climbing equipment', 'climbing trees', 'continuous cricket', 'cricket', 'cricket training', 'cross country skiing', 'cycling', 'diving', 'european handball', 'fencing', 'field hockey', 'football', 'football training', 'football umpiring', 'futsal', 'gymnastics', 'gymnastics class', 'high jump', 'hockey', 'horseback riding', 'horseriding', 'hurdles', 'indoor cricket', 'indoor soccer', 'jet skiing', 'jumping on trampoline', 'long jump', 'motor bike riding', 'motorbike', 'motorcycling', 'mountain biking', 'netball', 'netball practice', 'netball training', 'outdoor cricket', 'oztag', 'physical culture', 'playground activities', 'playing in playground', 'playing on equipment', 'racquetball', 'rhythmic gymnastics', 'riding bike', 'riding scooter', 'rockclimbing', 'rockclimbing gym', 'rollerblading', 'rollerskating', 'sailboarding', 'sailing', 'scooter', 'scootering', 'skim boarding', 'soccer', 'soccer refereeing', 'soccer training', 'softball', 'softball training', 'squash', 'surf lifesaving', 'surfing', 'T-ball', 'tennis', 'tennis match', 'tennis training', 'tip ', 'tip football', 'touch football', 'track cycling', 'trampoline', 'trampolining', 'triathlon', 'ultimate frisbee', 'volleyball', 'water polo', 'waterskiing', 'waterslide', 'weightlifting', 'white water rafting', 'windsurfing']},
    {
    name: 'high',
    activities: ['AFL', 'american football', 'aussie rules', 'australian rules football', 'BMX racing', 'boxercise', 'boxing', 'boxing classes', 'gaelic football', 'gridiron', 'ice hockey', 'ice skating', 'ice-skating', 'inline skating', 'judo', 'karate', 'kickboxing', 'kung fu', 'lacrosse', 'martial arts', 'martial arts training', 'mixed martial arts', 'moguls skiing', 'motocross', 'motor cross racing', 'riding rip stick', 'riding skateboard', 'rip stick', 'ripstick', 'rip-stick', 'rodeo', 'rough play', 'rugby', 'rugby football', 'rugby league', 'rugby league training', 'rugby training', 'skate park', 'skateboard', 'ski lessons', 'skiing', 'skiing downhill', 'snowboarding', 'tae kwon do', 'taekwondo', 'TKD', 'toboganning', 'wrestling']}];

 function setDropDown() {
    var $this = $(this);
    var activity = $this.val();
    var i;
    for (i = 0; i < risks .length; i++) {
        if (risks [i].activities.indexOf(activity) > -1) {
            var j;
            var NextddlRisk= $(this).parents("tr").find("[id^='lastYearRisk']")[0]; //find the parent tr, then find the risk dropdown
            for(j = 0; j < NextddlRisk.options.length; j++){
                if (NextddlRisk.options[j].innerHTML == risks [i].name){
                    NextddlRisk.selectedIndex = j;
                    break;
                }                    
            }
        break;
        }
    }


};

My question: is it possible to not have to press the TAB key for this to happen and for this to happen once the user has selected the activity from the list? It's not obvious to the user that the risk has been pre-populated at this stage as it's not appearing until they exit the field.

Upvotes: 1

Views: 647

Answers (1)

PSL
PSL

Reputation: 123739

I think i have a wild guess on what you are looking for. Is it that you want the dropdown to be populated with the actual value without having the user select an option from the autocomplete and navigate away (or press tab key)? if so you can subscribe to the autocomplete select event and this happens as you select an option from the autocomplete dropdown , call your setDropDown method here.

You code is too long and has some errors but here is a fiddle

  $("#lastYearSelect1")
        .autocomplete({
        source: availableTags,
        select: function (e, ui) {

           $(e.target).val(ui.item.value);
            setDropDown.call($(e.target));
        }
    })



cloned.find("[id^=lastYearSelect]")
            .autocomplete({
            source: availableTags,
                 select: function (e, ui) {

                 $(e.target).val(ui.item.value);
                setDropDown.call($(e.target));
            }
        })

Upvotes: 1

Related Questions