如何实现表格中仅更新当前下拉框对应的右侧选中值标签?
Hey there, let's sort out this issue for you!
The Problem
The root cause here is that your original code uses the global selector $(".item-name") every time a dropdown changes. This means it updates all elements with the item-name class across the entire table, which is why every label gets set to the same value no matter which dropdown you modify.
The Fix
We need to target only the label that's in the same table row as the dropdown you just changed. We can do this using jQuery's DOM traversal methods to pinpoint the right element without affecting others.
Here's the revised JavaScript code:
<script type="text/javascript"> $(window).load(function() { // Target only the dropdowns with class "item-number" $("select.item-number").change(function() { // Get the label of the selected option for THIS specific dropdown var selectedLabel = $(this).find("option:selected").attr('label') || "Description shows up here "; // Traverse up to the parent table row, then find the corresponding label inside it $(this).closest('tr').find(".item-name").text(selectedLabel); }).trigger('change'); // Trigger initial load to set labels correctly }); </script>
Key Changes Explained
- Target specific dropdowns: Changed
$("select")to$("select.item-number")so we only interact with your table's status dropdowns, not any other selects on the page. - Use
$(this): This refers directly to the dropdown that was just changed, so we don't accidentally grab values from other dropdowns. - Precise DOM traversal:
closest('tr')jumps up to the table row containing the active dropdown, thenfind(".item-name")grabs only the label in that row—this ensures we only update the label that belongs to the dropdown you modified. - Simplified label logic: No need for a loop here; we directly get the selected option's label from the current dropdown, with a fallback value if no label exists.
Quick Note on Your HTML
You're including the jQuery library inside every table row, which is redundant and can cause issues. Just add the jQuery script once at the top of your page (before your custom script) and remove the duplicates from each <tr>.
内容的提问来源于stack exchange,提问作者Βασιλική Παντελή

