JavaScript实现两个select框内容互换的简化方案咨询
Hey there! Your current approach of storing option values in arrays works, but we can simplify this a lot by directly swapping the entire content of the two <select> elements—no need to loop through options or build arrays at all.
First, let’s fix a small issue in your original HTML: both <select> elements have the same name and class (select_default1). That’ll cause problems when targeting them with jQuery, so let’s update the second one to use select_default2:
<select name="select_default1" class="select_default1"> <option value="">choose Columns</option> <option value=" 1"> 1</option> <option value=" 2"> 2</option> <option value=" 3"> 3</option> <option value=" 4"> 4</option> </select> <select name="select_default2" class="select_default2"> <option value="">choose Columns</option> <option value=" a"> a</option> <option value=" b"> b</option> <option value=" c"> c</option> </select>
The Simplified Solution
Using jQuery’s .html() method, we can grab the full inner content (all <option> elements) of each select box and swap them directly. Here’s the code:
// Bind change event to both select boxes $('.select_default1, .select_default2').on('change', function() { // Store the current content of each select const select1Content = $('.select_default1').html(); const select2Content = $('.select_default2').html(); // Swap the content $('.select_default1').html(select2Content); $('.select_default2').html(select1Content); // Optional: Reset the selected value to the default placeholder $(this).val(''); });
Why This Is Better Than Your Original Approach
- Less code: No looping through options or building arrays—we handle all options in one go.
- Preserves everything: Unlike storing just
valueattributes, swapping the full HTML preserves both the option values and their visible text. - Better performance: Fewer DOM operations mean faster execution.
Optional: Add a Condition for Swapping
If you only want to swap when a non-default option is selected (not the empty "choose Columns" option), add a quick check:
$('.select_default1, .select_default2').on('change', function() { if ($(this).val() !== '') { const select1Content = $('.select_default1').html(); const select2Content = $('.select_default2').html(); $('.select_default1').html(select2Content); $('.select_default2').html(select1Content); $(this).val(''); } });
That’s it! This approach is clean, concise, and does exactly what you need without unnecessary steps.
内容的提问来源于stack exchange,提问作者herbert mühlex

