Enter key not triggering submission in jQuery UI autocomplete field

I'm currently working on implementing the autocomplete feature following a tutorial, and while it's functioning, I'm facing an issue with submitting the form when the user selects an item and hits enter. Below is the Coffeescript code that I'm using, but for some reason, it doesn't work as expected. Can someone point out where I might be going wrong?

jQuery ->
  $('#search_bar').autocomplete( 
    source: $('#search_bar').data('autocomplete-source')
  ).keydown (e) ->
    $('#search_button').trigger "submit" if e.keyCode is 13

My goal is to also have the form submit upon selecting an item with a mouse click – not sure if this is achievable though?

Update: Attempted the following...

jQuery ->
  $('#search_bar').autocomplete
    source: $('#search_bar').data('autocomplete-source'),
    select: (event, ui) ->
      $(this).parents("form").submit()

While this method now works if you use the keyboard to select an item and press enter, selecting an item with a mouse click only sends the typed string, not the complete word from the auto-complete drop-down. Perhaps the search field needs to be updated with the text content on mouse-over?

Update 2: Problem solved! Just include the following at the end

focus: (event, ui) ->
   $('#search_bar').val(ui.item.value)

Answer №1

To handle the selection event, refer to the documentation available here. The autocomplete feature captures the enter key press to close the menu without propagation. The select event is triggered by both the enter key and mouse click. However, clicking may submit the form before updating the label value, so ensure to set the value first. Depending on your data source, consider using item.label instead of item.value.

$('#search_bar').autocomplete({
   source: $('#search_bar').data('autocomplete-source'),
   select: function(event, ui) {
         $(this).val(ui.item.value);
         $(this).parents("form").submit();  // This submits the form.
   }
})

A possible CoffeeScript conversion could be:

$('#search_bar').autocomplete(
   source: $('#search_bar').data('autocomplete-source'),
   select: (event, ui) ->
         $(this).val(ui.item.value).parents("form").submit();
)

Answer №2

If you're not familiar with coffee script, here's how you can achieve the same thing using javascript

http://jqueryui.com/demos/autocomplete/

To trigger a submit action when the user selects something, use the 'select' event:

$( ".selector" ).autocomplete({
    select: function(event, ui) {
        $('#theForm').submit();
    }
});

This should handle both cases - when something is selected either by pressing "Enter" or clicking on it.

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

Reacting with Angulatory: Response heads are not being transferred in applications

I'm facing an issue where the cookie containing my authentication token doesn't get passed along with my requests. After authenticating in Chrome, the response sets the cookie correctly, but it's not included in subsequent requests. This is ...

"Keeping your HTML content up-to-date with AngularJS dynamic updates

I've noticed that when I upload changes to my AngularJS HTML partial files, there is a caching issue where the old data is displayed. It takes a few refresh actions before the changes become visible. Is there a way to make these changes appear immedi ...

Top button disappears in Chromium browser after fade-in effect

I've encountered a very peculiar issue. Whenever I use the page down or fragmented identifier to jump to a specific div, my "go to top" image disappears. Here is the code snippet: HTML: <a title="Go to top" href="#" class="back-to-top"></ ...

Angular component equipped with knowledge of event emitter output

I have a custom button component: @Component({ selector: "custom-submit-button" template: ` <button (click)="submitClick.emit()" [disabled]="isDisabled"> <ng-content></ng-content> </butto ...

Suggestions for rendering this JSON format

I am attempting to iterate through this JSON format, I have tried following this method but I am a bit confused with my code How to iterate JSON array in JavaScript?. Also, I have a question, is this actually a valid JSON format or something different bec ...

Preventing file visibility in Three.js resource directory

Once a user clicks on a specific 3D model, I retrieve it from the server and render it in the browser using three.js. However, there is an issue when the user tries to access a model that is not free - they can easily view and download the STL file by go ...

Parsing form bodies in Express.js allows for easy extraction of data

Below is an example of a form: <!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> < ...

Interactive KML layer in ArcGIS mapping tool

Currently, I am working on enhancing an ArcGIS map by incorporating KML layers for interactivity. This is a simplified version of the code I am currently using: map = new Map("map", { basemap: "topo", center: [-108.663, 42.68], zoom: 6 }); parser.p ...

Is there a way to retrieve the text of a clicked button with execute_script?

Is there a way to extract text from a clicked button and send it back to Python? The user clicks the button in the Selenium WebDriver browser using the mouse. This is what I attempted: x=driver.execute_script("$(document).click(function(event){var te ...

Guide to saving an Object to a file (JSON) within the project directory using React Native for Debuggingpurposes

Feeling a bit overwhelmed trying to tackle this issue. My goal is to save data to a JSON file in real-time while debugging my application. I have a Redux store state that I want to organize neatly in a file for easier debugging, so exporting/writing the ob ...

Using CSS and JavaScript to hide a div element

In my one-page website, I have a fixed side navigation bar within a div that is initially hidden using the display:none property. Is there a way to make this side nav appear when the user scrolls to a specific section of the page, like when reaching the # ...

Sending a variable using the onchange function in jQuery

I have written a script to toggle the visibility of different divs based on selection var folder; $(function() { $('#teamleag').change(function() { if ($('#teamleag').val() == 'footballal') { $('# ...

Angular movie database using an API from an apiary

I'm struggling to create a link on movie posters that will lead to detailed movie information based on the movie ID. I have been going through their documentation, but I can't seem to get the api configuration to function properly. Every time I t ...

Delay reading body until npm request completes

My current challenge involves using npm request and cheerio to extract webpages and analyze their HTML structure. Everything works smoothly in scenarios where the HTML is available upon request. However, I am facing a problem when a website initially displ ...

Encountering vulnerabilities during NPM installation, attempting to fix with 'npm audit fix' but unsuccessful

While working on my react project, I decided to incorporate react-icons by running npm install react-icons in the command prompt. However, after some time, the process resulted in the following errors: F:\Areebs\React JS\areeburrub>npm in ...

Optimizing communication of time data in Laravel and Vue.js using Inertia

Currently, I am encountering an issue while working with Laravel Inertia and Vue.js. The problem arises when the time is transferred between Laravel and Vue.js, as it always converts to UTC automatically, which is not what I want. For instance, if I am u ...

Executing JavaScript code within ASP.NET Visual Basic

My current web application uses jQuery and JavaScript, but I want to add more features that are supported in ASP.net VB. However, I am unsure if the JavaScript can run after the VB code. Essentially, I would like the web app to follow this sequence: ...

Add a pair of assorted div elements to a shared container

I have two different sections with classes named "red" and "blue". By default, these sections are hidden. I want to duplicate them and display them in a single container named "cont". The red button appends the red section and the blue button appends the b ...

Quick Validator. Establishing a schema that relies on specific values

I have a situation where I need to differentiate between two types of users - teacher and student. The schema for a teacher looks like this: { username : string; firstName : string; lastName : string; type : 1; // 1 = teacher schoolId : o ...

React Router Link Component Causing Page Malfunction

Recently, I delved into a personal project where I explored React and various packages. As I encountered an issue with the Link component in React Router, I tried to find solutions online without any luck. Let me clarify that I followed all installation st ...