Reputation: 56
This is my selectize.js function
$("#addmobilenumbers").selectize({
inputClass: 'form-control selectize-input',
dropdownParent: "body",persist: false,
create: true //need to create and allow only digits
});
I want only numeric
(to enter only mobile numbers) input to create
here with min/max length
. How can I do it?
Upvotes: 3
Views: 652
Reputation: 20039
Using createFilter
and onInitialize
options
createFilter: validates the option before created using given regex
/^[0-9]{10}$/ - accepts only numbers between 0-9 of length 10 digits
onInitialize: event used to set maxlength / restrict input to numbers
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>
References
https://selectize.dev/docs.html#configuration
Upvotes: 2
Reputation: 28522
You can check that condition inside your create
function . Simply use $.isNumeric(input)
to check if the value is number and add your min/max length if this condition statisfy create your new option else use return false;
to prevent any default action.
Demo Code :
$("#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">
Upvotes: 2