Reputation: 3162
I am trying to get the number of letters and numbers in a field with jQuery.
Currently I am using this code and it doesn't work:
$("#sPassword1").on('input', function() {
var fieldValue = $(this).val();
var count = fieldValue.length;
var countL = fieldValue.match(/([A-z])/g).length;
var countN = fieldValue.match(/([0-9])/g).length;
console.log(count);
console.log(countL);
console.log(countN);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='password' id='sPassword1' value='abc12'/>
What am I doing wrong? :(
Upvotes: 0
Views: 981
Reputation: 2585
thats it
var countL = 0,
countN = 0;
$("#sPassword1").on('input', function() {
var fieldValue = $(this).val();
if ((/([A-z])/g).test(fieldValue)) countL += 1;
if ((/([0-9])/g).test(fieldValue)) countN += 1;
console.log(countL);
console.log(countN);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="sPassword1" type="text" value="">
Upvotes: 1
Reputation: 564
You forget to control the match function return null.
$( "#sPassword1" ).on('input', function() {
var fieldValue = $(this).val();
var count = fieldValue.length;
var match1= fieldValue.match(/([A-z])/g);
var match2= fieldValue.match(/([0-9])/g);
var countL = 0;
var countN = 0;
if ( match1 != undefined ){
countL = match1.length;
}
if ( match2 != undefined ){
countN = match2.length;
}
console.log(countL + " " +countN );
});
Upvotes: 1
Reputation: 21694
This works for me, it seems like the only thing missing is handling when there are no matches - the match wouldn't return an empty array, but a null value. See the RegExp lines:
$("#sPassword1").on('input', function() {
var fieldValue = $(this).val();
var count = fieldValue.length;
var countL = (fieldValue.match(/([A-z])/g) || []).length;
var countN = (fieldValue.match(/([0-9])/g) || []).length;
console.log({ count, countL, countN, fieldValue });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="sPassword1" />
Upvotes: 1