P粉0630399902023-08-14 14:21:09
Let's simplify things, create a separate function and apply your logic on the text field based on that function.
Example:
$('#dropdown').change(function() { var selectedOption = $(this).val(); check(selectedOption); }); $('#inputField').on('input', function() { var selectedOption = $('#dropdown :selected').val(); check(selectedOption); }); function check(inp) { var value = $('#inputField').val(); if (inp === 'fixed') { $('#inputField').attr('maxlength', '20'); var formattedValue = '₹' + value.replace(/\D/g, '').replace(/(\d)(?=(\d{3})+(?!\d))/g, ','); $('#inputField').val(formattedValue); } else { $('#inputField').attr('maxlength', '2'); var formattedValue = value.replace(/\D/g, '') + '%'; $('#inputField').val(formattedValue); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="dropdown"> <option value="fixed">固定值</option> <option value="percentage">百分比</option> </select> <input type="text" id="inputField">