Search code examples
javascriptesriarcgis-js-api

Search Widget - How to determine if "Enter" was pressed or result was selected?


I have a search box which throws up certain auto-suggested values when an address is searched for.

Now there are way ways in which a search event is fired:

  1. User starts typing an address (ignores the auto-suggested values) and hits Enter key
  2. User starts typing an address and midway through the process, selects a value from the auto-suggested list

In this scenario, is there a way I can figure out whether a selection was made or the Enter key was pressed in the event handler?

Javascript

var esriMap = new Map("esriMap", {
    basemap: "topo",
    center: [-12.4260, 31.3403],
    zoom: 12
});
var search = new Search({
   map: esriMap,
}, dom.byId("esriSearch"));
search.startup();
search.on("select-result", searchboxResult); // the event handler

function searchboxResult(e)
{
  // determine "Enter" key versus "Selection from auto-suggest"
}

Solution

  • Ofcourse, there is a way to figure out whether a selection was made or the Enter key was pressed while showing selection on the map.

    Below is the working code to implement this-

    require([
    
            "esri/map",
            "esri/dijit/Search",
            "dojo/on",
            "dojo/domReady!"
    
          ], function (Map, Search, on) {
             var map = new Map("map", {
                basemap: "gray",
                center: [-120.435, 46.159], // lon, lat
                zoom: 7
             });
    
             var search = new Search({
                map: map
             }, "search");
             search.startup();
             
            var isEnter= false;
            on(search.inputNode, "keypress", function(evt){
              isEnter = evt.keyCode == 13;
            });
            
            search.on("select-result", searchboxResult); 
    
             function searchboxResult(e)
               {
                alert(isEnter?"By Enter Selection": "By Suggestion Selection");
                // determine "Enter" key versus "Selection from auto-suggest"
              }
    
          });
    html,
          body,
          #map {
             height: 100%;
             width: 100%;
             margin: 0;
             padding: 0;
          }
          #search {
             display: block;
             position: absolute;
             z-index: 2;
             top: 20px;
             left: 74px;
          }
    <link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/themes/calcite/dijit/calcite.css">
       <link rel="stylesheet" href="https://js.arcgis.com/3.18/esri/themes/calcite/esri/esri.css">
    
    <script src="https://js.arcgis.com/3.18/"></script>
    
    <body class="calcite">
       <div id="search"></div>
       <div id="map"></div>
    </body>

    Hoping this will help you :)