JSFiddle - React, Tailwind, and code Playground

by ysuper

HTML

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- Select2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<!-- Select2 i18 中文翻譯 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/i18n/zh-TW.js"></script>

<h1>select2 多選限制範例</h1>
<form method="post">
	<input class="need" id="need" placeholder="請輸入幣值種類數量" required>
  <select id="currency" name="currency[]" multiple></select>
	<input type="button" id="button" value="取貨幣值">
</form>

JavaScript

/* pre_currency = ""
$(document).ready(function() {
	record_status()
});

function record_status() {
  pre_currency = $("#currency").val()
	console.log(pre_currency)
}

$("#button").click(function() {
  console.log($("#currency").val())
})

$("#currency").change(function() {
	if ($("#need").val() == "") {
		alert("請先填寫幣值種類數量!")
		$("#currency").val(pre_currency)
	}
	console.log(parseInt($("#need").val()))
	console.log($("#currency").val())
	console.log(parseInt($("#currency").val().length))
	if (parseInt($("#currency").val().length) > parseInt($("#need").val())) {
		alert("數量過多!")
		console.log(pre_currency)
		$("#currency").val(pre_currency)
	}	else {
	  record_status()
	}
}) */

$(function() {
	$("#currency").select2({
		language: 'zh-TW',
		width: '100%',
		maximumInputLength: 3, // 最多字元限制
		minimumInputLength: 0, // 最少字元才觸發尋找, 0 不指定
		maximumSelectionLength: 5,
		tags: false, // 當找不到可以使用輸入的文字
    multiple: true,
		data: [
			{ id: "AED", text: "AED" },
			{ id: "AFN", text: "AFN" },
			{ id: "ALL", text: "ALL" },
			{ id: "AMD", text: "AMD" },
			{ id: "ANG", text: "ANG" },
			{ id: "AOA", text: "AOA" },
			{ id: "ARS", text: "ARS" },
			{ id: "AUD", text: "AUD" },
			{ id: "AWG", text: "AWG" },
			{ id: "AZN", text: "AZN" },
			{ id: "BAM", text: "BAM" },
			{ id: "BBD", text: "BBD" },
			{ id: "BDT", text: "BDT" },
			{ id: "BGN", text: "BGN" },
			{ id: "BHD", text: "BHD" },
			{ id: "BIF", text: "BIF" },
			{ id: "BMD", text: "BMD" },
			{ id: "BND", text: "BND" },
			{ id: "BOB", text: "BOB" },
			{ id: "BRL", text: "BRL" },
			{ id: "BSD", text: "BSD" },
			{ id: "BTN", text: "BTN" },
			{ id: "BWP", text: "BWP" },
			{ id: "BYN", text: "BYN" },
			{ id: "BZD", text: "BZD" },
			{ id: "CAD", text: "CAD" },
			{ id: "CDF", text: "CDF" },
			{ id: "CHF", text: "CHF" },
			{ id: "CLP", text: "CLP" },
			{ id: "CNY", text: "CNY" },
			{ id: "COP", text: "COP" },
			{ id: "CRC", text: "CRC" },
			{ id: "CUC", text: "CUC" },
			{ id: "CUP", text: "CUP"...