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

The Angular scope fails to reflect changes on the view

In this angular ng-click event, I have the following code: eventApp.controller('DetailEventController', ['$scope', '$http', '$compile', '$timeout', function ($scope, $http, $compile, $timeout, uiCalendarCon ...

Understanding Vue.js - encountering the error message "property or method is not defined"

Recently, I've come across an issue that seems to be common among many people, but for some reason, I am unable to find a solution despite looking at similar questions. The problem arises when I use a v-for in a Vue Component and the array value cons ...

Obtaining the source code in CKEditor while in edit mode with Rails

As a Rails developer, I recently utilized CKEditor in one of my applications. After writing a sample HTML source code in the editor and submitting it, the code displayed properly on the front-end as a GUI. However, when attempting to edit the source code f ...

Having trouble loading select2 using PHP/Ajax/JSON even though I can see the data in the inspector

I encountered a puzzling issue after deploying my web application from a Windows (XAMPP environment) to a Linux Server. Despite everything working perfectly on Windows, I am now facing a frustrating problem that has left me stumped. I have scoured through ...

What is the reason behind the effectiveness of this prime number verifier?

Take a look at this code snippet that effectively checks whether a number is prime: var num = parseInt(prompt("Enter a number:")); var result = "Prime"; for (var i = 2; i < num; i++) { if (num % i === 0) { result = "Not Prime"; break; } } ...

Unable to retrieve HTML content through a Node.js server

I created a HTML webpage that includes .css, images and JavaScript files. However, when I start my node server using the command below: app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); The webp ...

Generate random images and text using a script that pulls content from an array

My goal is to have my website refresh with a random piece of text and image from an array when a button is clicked. I have successfully implemented the text generation part, but I am unsure how to incorporate images. Here is the current script for the text ...

"Pushing elements into an array does not function properly within a promise

I'm having trouble with my code - the push method isn't working and it's not returning anything. import {nearbyUsers, getLatitude, getLongitude} from './helper' const users = [] nearbyUsers(session, getLatitude(), getLongitude()).t ...

Jquery onchange event fails to fire

$('#selectclassid').trigger("change"); $('#selectclassid').on('change', function() { }); When trying to manually trigger the onchange event, it does not seem to be firing as expected. Although this format is commonly seen ...

What is the method for inputting multi-line strings in the REST Client extension for Visual Studio Code?

Clarification There seems to be some confusion regarding the nature of the data I am storing. I am developing a code snippet web application using Express.js and MongoDB. The purpose is not to store executable code for later use; instead, I am saving snipp ...

A guide on assigning specific (x, y) coordinates to individual IDs within the tree structure

When attempting to calculate the positions of each ID in order to arrange them hierarchically on the canvas, I encounter some challenges. Whether it's organizing them into a tree structure or multiple trees resembling a forest, one restriction is that ...

Sending data between two elements when a jQuery event is triggered

As a JavaScript beginner, I am facing an issue where I need to push data from an h1 tag to a textarea. My website is built using WooCommerce and when a visitor clicks on a product, a chat box with the product title opens. Currently, I have successfully p ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

Delete JavaScript functions and events from memory once the JavaScript code has been removed from the HTML file

I am encountering a situation with my website where popups loaded via ajax also load JavaScript code, which I want to remove when the popup is closed. The main site code looks like this: <body> ... <div id="popup" style="display:none"> < ...

Organizing AngularJS Data by Initial Letter with the <select></select> HTML Element

I'm trying to figure out how to filter an ng-repeat function based on the first letter of each option. For example, I want to filter a set of array or string so that only options starting with "A" or "B" are displayed. Can anyone help me with this? H ...

The array element is not being shown in the id "main" when using a for loop with the onchange function

I've been using document.write to display specific content, but it seems to be removing other elements from the page. Is there a way for me to display this loop inside the element with id="main" without losing any content? When I attempt to use docume ...

Guide to establishing a connection to the Companies House API: Essential guidelines on setting up cURL headers and requisite API key specifications

I am attempting to establish a connection with the UK Companies House API, preferably using JavaScript. However, I am currently trying to set up this PHP version. How can I obtain access to the API using an API key? PHP: public function GetCompanyHouse( ...

Exploring the world of JMeter: capturing sessions with JavaScript and jQuery

I need to capture a user session in order to conduct a performance test. I have been using the JMeter HTTP(S) Test Script Recorder, but unfortunately it is not recognizing javascript and jquery. The error message I'm receiving is: JQuery is not def ...

React: Updating State with the Spread Operator and Array Method to Add Elements to an Array

Link to my jsfiddle code snippet: https://jsfiddle.net/ilikeflex/r2uws1ez/30/ I've been attempting to update the state in React by accessing the previous state. There are three different cases where I'm trying to achieve this, but I'm havin ...

Is there a way for me to dynamically decide whether to use the append or prepend function?

Utilizing jQuery to retrieve data from the controller and populate a calendar represented by a table with days in columns. Implementing functionality for navigating between previous week / next week, as well as previous day / next day. The four scenarios s ...