Issues with Autofocus while Searching and Selecting from Dropdown menu

Here is the JavaScript code I am using:

<script type="text/javascript">
    function handleSelectionChange(selectElement, nextField) {
      nextField.focus();
    }
    
    function handleKeyPress(event, currentField, nextField) {
      if (event.key === "Enter") {
        event.preventDefault();
        nextField.focus();
      }
    }
  </script>

This is the form I have created:

<form action="incoming.php" method="post" >
                                            
<input type="hidden" name="pt" value="<?php echo $_GET['id']; ?>" />
<input type="hidden" name="invoice" value="<?php echo $_GET['invoice']; ?>" />
<select name="product"  onchange="handleSelectionChange(this, qty)" style="width:300px; "class="chzn-select" required autofocus>
<option></option>
    <?php
    try {
        include('../connect.php');
        $result = $db->prepare("SELECT * FROM products");
        $result->execute();
    
        // Code to generate dropdown options goes here
    } catch (PDOException $e) {
        echo "Database Error: " . $e->getMessage();
    }
    
        for($i=0; $row = $result->fetch(); $i++){
    ?>
        <option value="<?php echo $row['product_id'];?>"><?php echo $row['product_code']; ?> - <?php echo $row['gen_name']; ?> - <?php echo $row['product_name']; ?> | Expires at: <?php echo $row['expiry_date']; ?></option>
    <?php
                }
            ?>
</select>
<input type="number" onkeydown="handleKeyPress(event, this, price1)" name="qty"  value="" min="1" placeholder="Qty" autocomplete="off" style="width: 300px; height:30px; padding-top:6px; padding-bottom: 4px; margin-right: 4px; font-size:15px;" / required>
<input type="hidden" name="discount" value="" autocomplete="off" style="width: 68px; height:30px; padding-top:6px; padding-bottom: 4px; margin-right: 4px; font-size:15px;" />
<input type="number" onkeydown="handleKeyPress(event, this, button)" name="price1" value="" autocomplete="off" placeholder="Price" style="width: 300px; height:30px; padding-top:6px; padding-bottom: 4px; margin-right: 4px; font-size:15px;" / required>
<input type="hidden" name="date" value="<?php echo date("m/d/y"); ?>" />
<Button type="submit" name="button" class="btn btn-info" style="width: 123px; height:35px; margin-top:-5px;" /><i class="icon-plus-sign icon-large"></i> Add</button>
</form>

The issue I'm facing is that I want the select element to be autofocused when the page loads. However, the autofocus attribute is not working as expected. I noticed that removing the "class="chzn-select" from the select tag enables autofocus to work, but adding it back disables the functionality. Any help with resolving this would be greatly appreciated.

Answer №1

Give this a try:

Start by adding an id attribute to the product select element, and then include

document.getElementById("product").focus()

at the beginning of your script section. Please note that I have removed some PHP code, which you can insert back into your code as needed.

document.getElementById("product").focus()

function handleSelectionChange(selectElement, nextField) {
  nextField.focus();
}
    
function handleKeyPress(event, currentField, nextField) {
  if (event.key === "Enter") {
    event.preventDefault();
    nextField.focus();
  }
}
<form action="incoming.php" method="post" >                                                
    <input type="hidden" name="pt" value="" />
    <input type="hidden" name="invoice" value="" />
    <select name="product" id="product"  onchange="handleSelectionChange(this, qty)" style="width:300px; "class="chzn-select" required>
        <option>Prod1</option>
        <option>Prod2</option>
    </select>
    <input type="number" onkeydown="handleKeyPress(event, this, price1)" name="qty"  value="" min="1" placeholder="Qty" autocomplete="off" style="width: 300px; height:30px; padding-top:6px; padding-bottom: 4px; margin-right: 4px; font-size:15px;" required />
    <input type="hidden" name="discount" value="" autocomplete="off" style="width: 68px; height:30px; padding-top:6px; padding-bottom: 4px; margin-right: 4px; font-size:15px;" />
    <input type="number" onkeydown="handleKeyPress(event, this, button)" name="price1" value="" autocomplete="off" placeholder="Price" style="width: 300px; height:30px; padding-top:6px; padding-bottom: 4px; margin-right: 4px; font-size:15px;" required />
    <input type="hidden" name="date" value="" />
    <Button type="submit" name="button" class="btn btn-info" style="width: 123px; height:35px; margin-top:-5px;" /><i class="icon-plus-sign icon-large"></i> Add</button>
</form>

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

Guide on programmatically choosing an option within a variable with the help of jQuery

Imagine having a variable named html, which holds select options like this: var html = '<select>'+ '<option value="10">10</option>'+ '<option value="20">20</option>'+ ...

Concealing tooltip when button is clicked using jQuery

I am facing an issue where the tooltip does not hide on button click. Below is the code for the button in question: <button class="btn btn-outline-inverse ajax_addtocart additems ...

Why does the jQuery "alert" function work, but the image "src" setting is being overlooked?

Building on the previous inquiry: Can't I use JQuery inside my FancyZoom popup? The solutions provided in response to that query resolved the issue of consistently triggering our Hello World alert within our FancyZoom popup. However, our ultimate g ...

Images cascading like a downpour on a canvas (Javascript)

I have been experimenting with canvas, attempting to create a simulation of random falling objects. I've successfully drawn the background image, but I'm having trouble with the second image that is supposed to simulate a rain drop. I've ma ...

Navigating the Angular Element: A Guide to Clicking Buttons within Modal-Dialogs Using Protractor

I am currently creating an automation test for an angular application using the protractor framework. Test scenario: Click on the "Create PDF Report" button A modal-dialog window will appear Click on the "Run Report Now" button within the modal-d ...

Using Angular JS services and controllers in separate files may result in errors

Within my angularjs project, I manage the following files: /index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-wid ...

JavaScript code that functions similarly to VLOOKUP, allowing you to map input values from one field to

As a beginner in HTML and JavaScript, I am trying to create a simple form that automatically populates a specific "Customer Code" when a "Customer Name" is selected from a dropdown list (similar to an Excel VLOOKUP). However, the examples I found on Stack ...

Discovering identical objects in two arrays in Angular using TypeScript is a breeze

I've hit a roadblock with a TypeScript problem in my Angular service. I have an array of ingredients: private ingredients: Ingredient[] = [ new Ingredient('farina', 500), new Ingredient('burro', 80), new Ingredient('ucc ...

What could be the reason behind the failure of this computed property to update in my Vue 3 application?

As I transition from Vue's Options API to the Composition API, I decided to create a small Todo App for practice. Within App.vue, my code looks like this: <template> <div id="app"> <ErrorMessage v-if="!isVali ...

Exploring the Possibilities of Message Embeds in Discord using JavaScript

My goal is to teach my bot how to scan the description of embeds for a specific phrase. After reviewing the documentation at https://discord.js.org/#/docs/main/v11/class/MessageEmbed?scrollTo=description, it appears that I need to implement code similar to ...

Leveraging $(this) within an AJAX callback function

$(".itemInto").click(function(){ var a = $(this).siblings(".itemName").html(); $.ajax({ type: "POST", dataType: "json", url: "process.php", data: {a:a}, success: function(data) { alert (data); // 20 ...

Tips for customizing the appearance of ToggleButton in material-ui

Currently, I'm working on customizing the ToggleButton in order to change the default color when it is selected. However, my attempts have been fruitless so far. const customizeStyles = makeStyles((theme) => ({ toggleButtonSelected: { &q ...

How can we effectively create reusable modals in React with the most efficient approach?

Currently, I am developing an application using React and Material UI. In order to streamline the use of Modals across multiple pages, I have implemented a global modal context that dynamically populates the modal with different props based on state change ...

Achieving a perfect circle can be accomplished by setting both the width and height to the same

Trying to make the height of an element equal to its width For example, aiming for a perfect circle Although the console displays equal values, the resulting height is noticeably greater than the width $('button').on('click', funct ...

I am having trouble receiving responses when using mentionsInput in my Laravel project

Why am I not receiving any response while using the mentionsInput feature in my Laravel project? The data is correctly coming in JSON format, which I have verified. $(document).ready(function() { var token = $("#csrf-token").val(); $("textarea.menti ...

Retrieving HTML Source Code in Android Studio

I am having trouble with testing this function even though the permissions are correctly set in the manifest file. Can anyone help me figure out what I'm doing wrong? public void fetchHTMLContent() throws Exception { URL url = new URL("http:/ ...

Steps for adding a view to an element

Can someone help me with the syntax needed to append my template within the div "#draggableContainers"? I feel like I'm overlooking something simple. <html xmlns="http://www.w3.org/1999/xhtml"> New Page Title <script src="https://ajax ...

Resolve the issue of text overflow in PrimeNG Turbo Table cells

When utilizing Primeng table and enabling the scrollable feature, the table is expected to display a scrollbar while ensuring that the text within the cells does not overflow. Unfortunately, this expected behavior is not occurring. To see an example of th ...

Learn the method for printing CSS outlines and background colors in IE8 using JQuery's printElement feature

Printing my HTML calendar table in Chrome results in a perfect display. However, when I try to print it in IE8, the background colors and images are not included. Despite following steps from a helpful post on setting it as the default option, there were n ...

Experience the mesmerizing motion of a D3.js Bar Chart as it ascends from the bottom to the top. Feel free to

Here is the snippet of code I am working with. Please check the link for the output graph demonstration. [Click here to view the output graph demo][1] (The current animation in the output is from top to bottom) I want to animate the bars from Bottom to ...