0

I'm currently using Google Places Autocomplete with great success. What I would like to do is force the selection of the first option in the autocomplete list but ONLY if there is just one option displayed.

I do not like the idea of forcing the selection of the first option if there are many options displayed. Today I noticed that a large UK property website, Rightmove, forces the same behaviour as I'm requesting. It seems a lot more user friendly approach.

I have searched all of the questions on SO and this hasn't been asked before. Does anyone know how this can be coded?

luke_mclachlan
  • 1,035
  • 1
  • 15
  • 35

1 Answers1

0

My solution

<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <title>Place Autocomplete</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

  <script src="https://code.jquery.com/jquery-1.11.2.js" type="text/javascript"></script>

  <script src="https://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places&amp;language=en" type="text/javascript"></script>

  <script type="text/javascript">
    
      var autocomplete; 
      var place;

      function initialize() 
      {
        var options       = {types: ['(cities)']};
        var input         = document.getElementById('searchTextField');
        
        autocomplete  = new google.maps.places.Autocomplete(input, options);

        google.maps.event.addListener(autocomplete, 'place_changed', function() {
          fillInPlace();
        });
      }

      function fillInPlace() {
        place = autocomplete.getPlace();
        var $address = $(place['adr_address']);
        $('#resultTextField').val($address.text());
      }

      $(document).on('ready', function(){
          $("#searchTextField").on('focusout', function(e){
              setTimeout(function() {
                    $("#searchTextField").val('');
              }, 1000);
          });
      })
      
      google.maps.event.addDomListener(window, 'load', initialize);

  </script>
</head>

<body>
  <form class='form'>
    <div class="form-group">
      <div class="col-xs-12">
        <label for="searchTextField">City</label>
      </div>
      <div class="col-xs-12">
        <input id="searchTextField" type="text" placeholder="Search" autocomplete="on" class='form-control pull-left' style='width:40%; margin-right:3px;'>
        <input id="resultTextField" type="text" placeholder="" autocomplete="on" class='form-control pull-left' disabled='disabled' style='width:55%'>
      </div>
    </div>
  </form>
</body>
</html>
Ricardo Canelas
  • 2,280
  • 26
  • 21