Using ASP.Net web forms with Bing Map AutoSuggest API

Currently, I am integrating the Bing Map API into a web forms application for address lookup functionality. I attempted to follow this method, which worked seamlessly in an HTML form.

However, when I tried implementing it in an ASP.NET Web Form (with the runat=server" attribute), I encountered some issues.

While I am able to see the suggestions and select the desired item using arrow keys followed by Enter key press, the values are not being set in the input control upon selection with the enter key. It seems that only mouse clicks correctly populate the input with selected values within a web form environment.


    <script type="text/javascript>
    function bingMapsReady() {
        Microsoft.Maps.loadModule("Microsoft.Maps.AutoSuggest", {
            callback: onLoad,
            errorCallback: logError,
            credentials: 'xxxxxxx'
        });

        function onLoad() {
            var options = { maxResults: 8 };
            initAutosuggestControl(options, "searchBox", "searchBoxContainer");
            initAutosuggestControl(options, "searchBoxAlt", "searchBoxContainerAlt");
        }
    }

    function initAutosuggestControl(
        options,
        suggestionBoxId,
        suggestionContainerId
    ) {
        var manager = new Microsoft.Maps.AutosuggestManager(options);
        manager.attachAutosuggest(
            "#" + suggestionBoxId,
            "#" + suggestionContainerId,
            selectedSuggestion
        );

        function selectedSuggestion(suggestionResult) {
            document.getElementById(suggestionBoxId).innerHTML =
                suggestionResult.formattedSuggestion;
        }
    }


    function logError(message) {
        console.log(message);
    }
</script>

        <div class="col-lg-6">
        <div class="form-group">
            <label for="searchBox">Address</label>
            <div id="searchBoxContainer">
                <input class="form-control" type="text" id="searchBox" /></div>
        </div>
        <div class="form-group">
            <label for="searchBoxAlt">Alternative Address</label>
            <div id="searchBoxContainerAlt">
                <input class="form-control" type="text" id="searchBoxAlt" /></div>
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>

<script
    type="text/javascript"
    src="https://www.bing.com/api/maps/mapcontrol?key=xxxxxxx&callback=bingMapsReady" async defer></script>

Answer №1

To ensure the desired functionality, one idea is to restrict the submission of a form when the enter button is pressed by adding the following code snippet:

document.querySelector('form').addEventListener('submit', function (e) {
        e.preventDefault();
}, false); 

Alternatively, you can target specific input elements as shown below:

 function onLoad() {
     var options = { maxResults: 8 };
     initAutosuggestControl(options, "searchBox", "searchBoxContainer");
     initAutosuggestControl(options, "searchBoxAlt", "searchBoxContainerAlt");

     disableInputSubmit(document.querySelector('#searchBox'));
     disableInputSubmit(document.querySelector('#searchBoxAlt'));
 }

Here's the function used to prevent the Enter key from submitting an input element:

function disableInputSubmit(element) {
     element.addEventListener('keypress', function(e){
         if (e.which === 13) // Enter key = keycode 13
         {
            e.preventDefault();
         }
     },false);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Easily conceal and reveal elements using Svelte in a straightforward manner

I'm looking for a straightforward method to hide and show an element using a button in Svelte. Can someone guide me on how to achieve this? Additionally, I'm curious if it's easier to accomplish this task with vanilla JavaScript. ...

Does the user need to download the scripts from Google API multiple times during the insertion process?

Concerned about the potential need for multiple downloads of a script from an unknown location on the user's computer, I would like to explore options to mitigate this issue. Specifically, I am considering creating a condition to check the download st ...

Unable to insert HTML code into a div upon clicking an image button

I am in the process of developing a website dedicated to radio streams, and I was advised to utilize Jquery and AJAX for loading HTML files into a div upon button click. This way, users wouldn't have to load an entirely new page for each radio stream. ...

SWR Fails to Recognize Environment Variables

I'm struggling to utilize ENV variables when using the SWR hook for data fetching. My current approach is as follows: const videoURLWithEnv = `https://youtube.googleapis.com/youtube/v3/search?part=snippet&channelId=UCwkj9jcrMZCcbcIa6nF5LNQ&ma ...

Manage Datatables: Efficiently toggling the display of multiple rows in a loop

This specific inquiry pertains to the Datatables plug-in for JQuery. I am working with an HTML table that contains entries in 3 languages: en, ru, fr. When a language is selected, the entries in the other two languages should be hidden. For instance, if E ...

The settings of the button return to their default state once it is clicked on

I've been working on a small project and I added a button with hover and CSS effects. However, the issue is that once the button is clicked, it reverts back to its basic state without any of the CSS properties applied. I attempted to troubleshoot if ...

What is the best way to store HTML in a variable as a string?

Imagine if I have a variable: let display_text = "Cats are pawsome!" I aim to show it as such: <div> <b>Cats</b> are pawsome! </div> To be clear, dynamically enclose the word "cats" whenever it shows up. ...

The error message "Uncaught TypeError: Cannot read property 'length' of undefined" is commonly encountered in asp.net while using dataTables with zero config

I am encountering an issue with dataTables in my ASP.NET webforms application. The table is generated in the codebehind at Page_Load() and works fine on other pages, but for some reason, I am getting an error message on one specific page: "datatables.min.j ...

Unusual characters suddenly show up at the conclusion of a URL following a response.redirect in ASP.NET

Is anyone else experiencing odd characters like #_=_ at the end of the URI when using the Response.Redirect() method? These strange characters include a hash, underscore, equal sign, and another underscore together. I am unsure why these characters appear ...

Tips on integrating Next/Previous functionality for a modal Ajax popup

I have been utilizing a bPopup jQuery plugin to display ajax HTML files in a modal popup on my website. However, I am interested in enhancing this functionality to allow users to seamlessly navigate to the next slide within the modal without having to exit ...

Update the state when a button is clicked and send a request using Axios

Currently in my front end (using react): import '../styles/TourPage.css'; import React, { Component } from 'react'; import axios from 'axios' class TourPage extends Component { constructor(props) { super(p ...

Tips on utilizing Yolo V5 in C# with GPU acceleration

I have been struggling to get Yolo up and running on my GPU for the past few days. I attempted to use following their instructions to utilize the GPU, but it was unsuccessful. Other C# Yolo wrappers do not support the Yolov5 version that I specifically wa ...

What is the correct way to pass parameters when using the setState() function in React hooks?

I am working on a project where I have a list of country names. When a user clicks on one of the countries, I want to update the state with the name of the newly selected country. This state change will then trigger other changes in a useEffect(). The stat ...

The entry description function is not functioning properly when used with jGFeed

I have implemented jGFeed to extract data from an RSS Feed. Below is a snippet of the code I am using: $.jGFeed('http://feeds.bbci.co.uk/news/rss.xml', function(feeds){ // Check for errors if(!feeds){ ...

The issue of checkboxes not being sorted properly in Slick Grid

Currently, I am working on resolving a sorting issue within one of our applications using Slick Grid for grid implementation. The existing sort function, although functional, presents a challenge. While it successfully sorts columns, the checkbox associate ...

Using a Javascript while loop to iterate through an array and display the elements in the .innerHTML property

As a newcomer to Javascript, I am in the process of teaching myself. My current task is to develop a function that will display each element of the array AmericanCars with a space between them. I have successfully been able to show an individual element u ...

Vue component fails to render on a specific route

I am having trouble rendering the Login component on my Login Route. Here is my Login component code: <template> <v-app> <h1>Login Component</h1> </v-app> </template> <script> export default { } </script ...

A step-by-step guide to incorporating VeeValidate with vue-i18n

When a click event is triggered, I am able to change the language in vue-i18n. However, I am facing an issue with changing the vee-validate dictionary to match the same language. Main.js import VeeValidate from 'vee-validate' import validations ...

Setting up a service URL with parameters using a versatile approach

I am faced with a situation where I have over 200 service URLs that follow a specific format: serviceURL = DomainName + MethodName + Path; The DomainName and MethodNames can be configured, while the path may consist of elements such as Param1, Param2, an ...

The function setAttribute does not work with arrays

I'm facing an issue where I need to conditionally assign an attribute to each item in an array based on a radio button value. I have been able to set the required attribute on individual items, but I'm struggling to apply it to all elements in th ...