使用document.execCommand实现下拉框值自动复制到输入框的问题
Fix: Auto-fill Inputs Without Copy-Paste
Hey there! Let's resolve this issue for you. You don't need to use the deprecated document.execCommand('copy') to populate the #reg input—direct value assignment is far more reliable and straightforward.
What was wrong with the original approach?
document.execCommand('copy')is now deprecated and not recommended for modern web development.- Trying to copy text and then trigger a paste into
#regadds unnecessary complexity, and your code wasn't handling the paste action correctly anyway. - There was a minor typo in your button style:
background- colorshould bebackground-color.
Corrected Code
Here's the revised version that directly assigns the selected value to both inputs:
$('body').append(`<div id="selectDialog" title="Select Regex Type" style="text-align:center;display:none;"> <select id="listSelection"> <option value ="">None</option> <option value ="[a-z]+">Single Digit Integers</option> <option value ="^[0-9]">Multi Digit Number</option> <option value ="/^-?[0-9]+\.?[0-9]*$/">Decimal Number</option> </select> <div style="margin:10px"> <button id="closeSelection" style="background-color:#3B5E9E">save</button> </div> </div>`); $(function () { $("#selectDialog").dialog({ autoOpen: false }); $('#changePattern').on("click", function () { $("#selectDialog").dialog("open"); }); $("#listSelection") .change(function () { const selectedValue = $(this).val(); // Update changePattern input $("#changePattern").val(selectedValue).attr("patternMask", selectedValue); // Directly populate the reg input with the selected value $("#reg").val(selectedValue); }) .trigger("change"); $('#closeSelection').on("click", function () { $("#selectDialog").dialog("close"); }); });
Key Improvements Explained
- Direct Value Assignment: Instead of copying and pasting, we simply set
$("#reg").val(selectedValue)in thechangeevent of the dropdown. This ensures the value is immediately reflected in the#reginput. - Removed Deprecated Code: All instances of
select()anddocument.execCommand('copy')are removed since they're unnecessary here. - Fixed Style Typo: Corrected
background- colortobackground-colorso the button's background color displays correctly. - Cleaner Value Retrieval: Used
$(this).val()to get the selected value instead of$("#listSelection option:selected").val()—it's more concise and references the element that triggered the event directly.
Now when you select an option from the dropdown, both #changePattern and #reg inputs will automatically get populated with the selected value, no manual copy-paste required!
内容的提问来源于stack exchange,提问作者Supriya Bhart
相关产品推荐
相关产品推荐

