请求JS多选联动自动计数器实现代码(含正负值计算)
Hey there! Let's build out that JS counter for your trait selection form. I've refined your existing code to meet all your requirements, with cleaner logic that's easy to maintain even with 50+ options. Here's the implementation:
Updated HTML Structure
First, we'll adjust the input section to include your required X/Y/Z fields, plus an error message area for negative Z values:
<!-- Keep your existing library imports --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css"> <!-- Trait multi-select (keep your existing optgroups/options) --> <select name="rasgos" class="multipleChosen rasgos" multiple="true"> <optgroup label="Positivos"> <option value="Cuerpo grande">Cuerpo grande</option> <option value="Musculoso">Musculoso</option> <option value="Ágil">Ágil</option> <option value="Con reflejos">Con reflejos</option> <option value="Preciso">Preciso</option> <option value="Afortunado">Afortunado</option> <option value="Atento">Atento</option> <option value="Agraciado">Agraciado</option> <option value="Vivaz">Vivaz</option> <option value="Culto">Culto</option> <option value="Noble">Noble</option> <option value="Líder">Líder</option> <option value="Defensor">Defensor</option> <option value="Precavido">Precavido</option> <option value="Orador">Orador</option> <option value="Sagaz">Sagaz</option> <option value="Aprendizaje rápido">Aprendizaje rápido</option> <option value="Crematomano">Crematomano</option> <option value="Regateador">Regateador</option> <option value="Domador">Domador</option> </optgroup> <optgroup label="Negativos"> <option value="En los huesos">En los huesos</option> <option value="Débil">Débil</option> <option value="Lento">Lento</option> <option value="Vago">Vago</option> <option value="Glotón">Glotón</option> <option value="Sin reflejos">Sin reflejos</option> <option value="Sin puntería">Sin puntería</option> <option value="Torpe">Torpe</option> <option value="Dócil">Dócil</option> <option value="Honesto">Honesto</option> <option value="Obstuto">Obstuto</option> <option value="Mal oído">Mal oído</option> <option value="Feo">Feo</option> <option value="Estéril">Estéril</option> <option value="Aprendizaje lento">Aprendizaje lento</option> <option value="Testarudo">Testarudo</option> <option value="Tartamudo">Tartamudo</option> <option value="Disoluto">Disoluto</option> <option value="Ceguera">Ceguera</option> <option value="Enfermizo">Enfermizo</option> </optgroup> </select> <!-- New counter input fields --> <div class="counter-group"> <input type="text" disabled name="x_value" class="alin" value="10" placeholder="X: 正特征总和(初始10)"/> <input type="text" disabled name="y_value" class="alin" value="0" placeholder="Y: 负特征总和(无负号)"/> <input type="text" disabled name="z_value" class="alin" value="10" placeholder="Z: X-Y差值(非负)"/> <div class="error-alert" style="color: crimson; margin-top: 8px; display: none;">⚠️ Z值不能为负,请调整所选特征!</div> </div>
Core JavaScript Implementation
This code replaces your messy if chain with a maintainable value map, handles all your calculation rules, and integrates seamlessly with Chosen/Select2:
$(document).ready(function() { // Initialize your existing dropdown plugins $(".multipleChosen").chosen({ placeholder_text_multiple: "Rasgos" }); $(".multipleSelect2").select2({ placeholder: "Rasgos" }); // 1. Map each trait to its corresponding value (easy to update for 50+ options) const traitValueMap = { // Positive traits (negative values) "Cuerpo grande": -5, "Musculoso": -5, "Ágil": -5, "Con reflejos": -6, "Preciso": -6, "Afortunado": -6, "Atento": -4, "Agraciado": -5, "Vivaz": -4, "Culto": -4, "Noble": -4, "Líder": -6, "Defensor": -6, "Precavido": -6, "Orador": -5, "Sagaz": -5, "Aprendizaje rápido": -6, "Crematomano": -4, "Regateador": -4, "Domador": -5, // Negative traits (positive values) "En los huesos": 4, "Débil": 5, "Lento": 5, "Vago": 3, "Glotón": 3, "Sin reflejos": 6, "Sin puntería": 6, "Torpe": 5, "Dócil": 4, "Honesto": 4, "Obstuto": 5, "Mal oído": 4, "Feo": 5, "Estéril": 6, "Aprendizaje lento": 6, "Testarudo": 5, "Tartamudo": 4, "Disoluto": 3, "Ceguera": 8, "Enfermizo": 5 }; // 2. Handle trait selection changes $('.rasgos').on('change', function() { const selectedTraits = $(this).val() || []; let xTotal = 10; // X starts at 10 let yTotal = 0; // Y starts at 0 // Calculate sums based on selected traits selectedTraits.forEach(trait => { const value = traitValueMap[trait]; if (value < 0) { xTotal += value; // Add negative values to X (reduces the total) } else { yTotal += value; // Add positive values to Y } }); // Calculate Z and validate const zTotal = xTotal - yTotal; const errorElement = $('.error-alert'); // Update input displays $('input[name="x_value"]').val(xTotal); $('input[name="y_value"]').val(yTotal); // Handle non-negative Z rule if (zTotal >= 0) { $('input[name="z_value"]').val(zTotal); errorElement.hide(); // Enable form submission (adjust selector to match your submit button) $('button[type="submit"]').prop('disabled', false); } else { $('input[name="z_value"]').val('负值'); errorElement.show(); // Block form submission $('button[type="submit"]').prop('disabled', true); } }); });
Key Improvements & Explanations
- Maintainable Value Map: Instead of dozens of
ifstatements, we use a single object to link traits to their values. Adding/editing traits is as simple as updating this map. - Clear Calculation Logic: We separate positive/negative trait sums to match your X/Y requirements, with X starting at 10 by default.
- Error Prevention: Real-time validation checks if Z is negative, shows an alert, and blocks form submission until the issue is fixed.
- Seamless Integration: Keeps your existing Chosen/Select2 setup intact, so it works directly with your custom form builder.
内容的提问来源于stack exchange,提问作者Gender Holos
相关产品推荐
相关产品推荐

