i trying 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 tried using .val() setter 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 in chrome , safari didn't work. suggested in other questions tried 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 expected in firefox not in safari or chrome.
it giving number.contains
not function in console. suggest use $.contains
below works , good!!
$(document).ready(function(){ $('input[name=user_phone]').keyup(function() { var number = $('input[name=user_phone]').val(); if (!$.contains(number,'(') && !$.contains(number,')') && number.length === 2) { $('input[name=user_phone]').val('(' + number + ')'); } else if ($.contains(number,'(') && !$.contains(number,')') && number.length === 3) { $(this).val(number + ')'); } else if (!$.contains(number,'(') && $.contains(number,')') && number.length === 3) { $(this).val('(' + number); } }); });
Comments
Post a Comment