I want to remove space only when user selects text from dropdown,I am not able to do that. in option it should display as it is.
/* $("#input_13").find("option").each(function (index, option) {
$(option).html($(option).html().replace(/ /g,''));
}); */
$('#input_13').change(function() {
// Get the selected option
var selectedOption = $(this).find('option:selected');
// Get the current text, trim spaces, and set it back
var trimmedText = $.trim(selectedOption.text());
selectedOption.text(trimmedText);
// Optionally, update the value attribute if needed
// $(this).val(trimmedText);
console.log($("#input_13 option:selected").text())
});
<select id="input_13">
<option label=" sw" value="number:1902"> sw</option>
<option label=" s" value="number:1903"> s</option>
<option label=" dsdsdsds" value="number:1906"> dsdsdsds</option>
<option label=" swww" value="number:1905"> swww</option>
</select>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Here it should display trimmed value in selection.
Note:- Drop-down Selected value should be display only when displayed and in option it should display as it is.
Here is a version that uses data attributes to store the values
$(() => {
const handleOptionLabels = (selectElement, save=false) => {
$(selectElement).find('option').each(function() {
if (save) this.dataset.label = this.textContent; // Save initial text to data-label
else this.textContent = this.dataset.label; // Reset text from data-label
});
};
$('#input_13').on('change', function() {
handleOptionLabels(this); // reset
// Get the selected option
var selectedOption = $(this).find('option:selected');
// Get the current text, trim spaces, and set it back as the label
var trimmedText = $.trim(selectedOption.text());
selectedOption.text(trimmedText);
});
handleOptionLabels('#input_13', true); // initialise
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<select id="input_13">
<option value="number:1902"> sw</option>
<option value="number:1903"> s</option>
<option value="number:1906"> dsdsdsds</option>
<option value="number:1905"> swww</option>
</select>