这是我的selectize.js函数
$("#addmobilenumbers").selectize({
inputClass: 'form-control selectize-input',
dropdownParent: "body",persist: false,
create: true //need to create and allow only digits
});我只想要numeric (只输入手机号码)输入到这里的create与min/max length。我该怎么做呢?
发布于 2021-06-15 22:53:23
使用createFilter和onInitialize选项
createFilter:在使用给定的正则表达式创建之前验证选项
/^[0-9]{10}$/ - accepts only numbers between 0-9 of length 10 digitsonInitialize:用于设置最大长度/限制输入为数字的事件
this.$control_input.prop('maxlength', 10)
this.$control_input.on('input', function() {
this.value = this.value.replace(/[^\d]/g, '')
})
$("#addmobilenumbers").selectize({
inputClass: 'form-control selectize-input',
dropdownParent: "body",
persist: false,
create: true,
createFilter: /^[0-9]{10}$/,
onInitialize: function() {
this.$control_input.prop('maxlength', 10)
this.$control_input.on('input', function() {
this.value = this.value.replace(/[^\d]/g, '')
})
}
})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/js/standalone/selectize.min.js" integrity="sha512-pF+DNRwavWMukUv/LyzDyDMn8U2uvqYQdJN0Zvilr6DDo/56xPDZdDoyPDYZRSL4aOKO/FGKXTpzDyQJ8je8Qw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.13.3/css/selectize.default.min.css" integrity="sha512-H955AcCOE/fUjX4XWkN0FwjCYVV/zioSF6VpUKCcrGdR1Wa8paFWYixWYp85npbnx3i1kZCH4Rm4TRxut2+d5A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<select id="addmobilenumbers" multiple></select>
参考
发布于 2021-06-15 22:49:56
只需使用$.isNumeric(input)检查该值是否为number并添加最小/最大长度,如果满足此条件,则创建新选项,否则使用return false;阻止任何默认操作。
演示代码:
$("#addmobilenumbers").selectize({
inputClass: 'form-control selectize-input',
dropdownParent: "body",
persist: false,
plugins: ['remove_button'],
create: function(input) {
console.log($.isNumeric(input), input.length)
//check if no is numeric ,,and min/max length
if ($.isNumeric(input) && (input.length > 2 && input.length < 6)) {
return {
value: input,
text: input
} //create that tags...
} else {
console.log("can't add")
return false; //prevnt default...
}
}
});<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.8.5/css/selectize.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.8.5/js/standalone/selectize.min.js"></script>
<input type="text" id="addmobilenumbers">
https://stackoverflow.com/questions/58160749
复制相似问题