I am trying to set html input field value on keyup event using jquery.
<input style="width: 45%;" type="text" name="user_phone" value="" placeholder="Your phone number" />
First I tried using .val() setter like this.
http://jsfiddle.net/6xwzy81k/3/
$(document).ready(function(){
$('input[name=user_phone]').keyup(function() {
var number = $('input[name=user_phone]').val();
if (!number.contains('(') && !number.contains(')') && number.length === 2) {
$('input[name=user_phone]').val('(' + number + ')');
} else if (number.contains('(') && !number.contains(')') && number.length === 3) {
$(this).val(number + ')');
} else if (!number.contains('(') && number.contains(')') && number.length === 3) {
$(this).val('(' + number);
}
});
});
This worked fine in firefox but in chrome and safari it didn't work. Then as suggested in some other questions I tried it this way using .prop() instead of .val()
http://jsfiddle.net/6xwzy81k/2/
$(document).ready(function(){
$('input[name=user_phone]').keyup(function() {
var number = $('input[name=user_phone]').val();
if (!number.contains('(') && !number.contains(')') && number.length === 2) {
$('input[name=user_phone]').prop('value','(' + number + ')');
} else if (number.contains('(') && !number.contains(')') && number.length === 3) {
$(this).prop('value', number + ')');
} else if (!number.contains('(') && number.contains(')') && number.length === 3) {
$(this).prop('value', '(' + number);
}
});
});
The same thing happened, it worked as expected in firefox but not in safari or chrome.
since the error in your code was pointed out by the other answer here is an alternate solution. if you want to format the number in the form (###) ###-#### here is a solution that uses regex to first stip non-digits, then depending on the length of the actual digits, format them. tested in chrome and safari. also handles deletes/backspace
also used your fiddle
$(document).ready(function(){
$('input[name=user_phone]').keyup(function() {
var number = $('input[name=user_phone]').val();
var digits = number.replace(/[^0-9\.]+/g, '');
var lastDigitIndex = (digits.length < 10) ? digits.length : 10;
var key = event.keyCode || event.charCode;
if (key != 8 && key != 46) {
if (digits.length >= 3) {
var output = '(' + digits.substring(0, 3) + ') ';
if (digits.length >= 6) {
output += digits.substring(3, 6)
+ '-' + digits.substring(6, lastDigitIndex);
}
else {
output += digits.substring(3, lastDigitIndex);
}
$(this).val(output);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input style="width: 45%;" type="text" name="user_phone" value="" placeholder="Your phone number" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With