I want that user should not be able to enter text if he has more then 5 comma separated values in input box.
I have reached the value, but not sure. I think maxlength
dynamic should do the trick.
I am trying to apply below code, but not working -
require(["jquery"],function($) {
$("input.toEmail").keyup(function(e){
var inputEmail = $("input.toEmail").val();
var count = (inputEmail.match(/,/g) || []).length;
if(count >= 5){
e.preventDefault();
e.stopPropagation();
}
});
});
You can achieve it in this simple way.
Note:
"Split a string into an array of substrings"
"extracts parts of a string and returns the extracted parts in a new string"
"returns the array as a string"
$("input.toEmail").keyup(function(e){
var inputEmail = $(this).val();
var strArray = inputEmail.split(/,/g);
if(strArray.length >= 5){
this.value = strArray.slice(0, 5).join(',');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="toEmail"/>