You can detect the text of the selected option, compare it to the value (which is the same for user generated options) and then transofrm this before assigning it to the value of that option.
The code below will change the value to the first two letters of the country name.
Update: have now included the ability to add an option with a user defined value, i.e. en:England.
The code is fully commented.
Let me know if this wasn't what you wanted.
// Initialise select2
$('select').select2({
tags: true,
width: 330
})
// Detect change event
$("#country").change(function() {
// Get text of selected option
var selectText = $("#country option:selected").text();
// Check if value matches text
// i.e. if this is user generated
if ($(this).val() == selectText) {
// Check if colon is used
if (selectText.indexOf(":") !== -1) {
// Split text based on colon
var splitText = selectText.split(":");
// Create new option, mark as selected
var newOption = new Option(splitText[1], splitText[0], false, true);
} else { // If no colon found
// Create new option, mark as selected
// Take the first two letters and lower case them
var newOption = new Option(selectText, selectText.substr(0, 2).toLowerCase(), false, true);
}
// Append new option
$('#country').append(newOption);
// Prove we've changed the value
console.log($(this).val());
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
</head>
<body>
<select name="country" id="country">
<option value="th">Thailand</option>
<option value="vn">Vietname</option>
</select>
</body>
</html>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…