如何动态提交输入框值?点击分类链接填充表单触发POST搜索
Here's how you can achieve this with vanilla JavaScript, ensuring non-Latin characters are handled correctly via POST submission:
Step 1: Update Your Category Link
First, add a class to the <a> tag (to easily target it) and a placeholder href (to prevent default link behavior issues):
<div class="cbp-l-inline-title" style=" font-size: 18px;"> <span style="color: #0669b4">Generic Name:</span> <a class="generic-search-link" href="#"><?php echo $category[0]['generic_name'];?></a> </div>
Step 2: Add an ID to Your Search Form
Giving the form an ID makes it simpler to select in JavaScript:
<form id="generic-search-form" method="post" action="/search/index" class="input-group" style="width: 45%; margin-left: 646px"> <input type="text" name="search" id="search" class="form-control" minlength=3 placeholder="Generic" aria-label="Recipient's username" aria-describedby="basic-addon2"> <div id="suggesstion"></div> <div class="input-group-btn input-group-append"> <button class="btn btn-primary btn-outline-secondary" type="submit" name="submit">Search</button> </div> </form>
Step 3: Add the JavaScript Handler
This code will listen for clicks on the generic name link, populate the search input, and trigger the POST form submission:
document.addEventListener('DOMContentLoaded', function() { // Get all generic name links (works even if there are multiple) const genericLinks = document.querySelectorAll('.generic-search-link'); // Get references to the form and input field const searchForm = document.getElementById('generic-search-form'); const searchInput = document.getElementById('search'); // Attach click event to each link genericLinks.forEach(link => { link.addEventListener('click', function(e) { // Stop the link from navigating to the # anchor e.preventDefault(); // Get the clean generic name text const genericName = this.textContent.trim(); // Fill the search input with the generic name searchInput.value = genericName; // Submit the form using POST (matches your form's method) searchForm.submit(); }); }); });
Why This Works for Non-Latin Characters
By using the form's native submit() method, we're leveraging the POST request mechanism. This sends the search value in the request body instead of the URL, so non-Latin characters are properly encoded and transmitted without issues related to URL parameter limitations.
内容的提问来源于stack exchange,提问作者Iva Kobalava

