Datalist dropdown positioning fix
March 16, 2025 ยท AI Conversations
User
Assistant
To ensure the “ dropdown appears below the input field instead of to the side, you can use the following CSS:
### Solution:
.product-input {
position: relative;
display: inline-block;
width: 100%;
}
.product_code {
width: 100%;
font-size: 12px;
padding: 5px;
}
datalist {
position: absolute;
width: 100%;
max-height: 200px; /* Control height */
overflow-y: auto; /* Enable scrolling if many options */
border: 1px solid #ccc;
background: white;
z-index: 999;
}
option {
padding: 5px;
cursor: pointer;
}
### JavaScript Enhancement:
Since “ rendering behavior is browser-dependent and cannot be fully controlled by CSS, you might want to replace it with a “-like dropdown. The following JavaScript makes the dropdown appear below the input:
document.querySelectorAll('.product_code').forEach(input => {
input.addEventListener('focus', function () {
this.setAttribute('list', this.getAttribute('data-list-id'));
});
input.addEventListener('blur', function () {
setTimeout(() => this.removeAttribute('list'), 200); // Small delay to allow selection
});
});
### Modify HTML:
Ensure `data-list-id` is correctly set in the input.
<input autocomplete="off" list="" class="product_code drodpdown-<?php echo $product->get_id(); ?>" name="product_code" value="" style="font-size: 12px;" data-pid="<?php echo $product->get_id(); ?>" data-list-id="product_code-<?php echo $product->get_id(); ?>" placeholder="Enter or select the Product Code">
This should ensure the dropdown appears directly below the input and functions more predictably across browsers.