javascript - Form Validation Jquery object -
i trying format phone number field based on country .the logic works fine when user fill in details not work when country changed , filled in again. ex: filled in form germany , without reloading page if try change county , fill in phone "+" being added though format different.
$(document).ready(function($){ $('#country').on('change', function() { if ( this.value == 'us' || this.value == 'ca') { $('#c_busphone') .keydown(function (e) { var key = e.charcode || e.keycode || 0; $phone = $(this); if (key !== 8 && key !== 9) { if ($phone.val().length === 4) { $phone.val($phone.val() + ')'); } if ($phone.val().length === 5) { $phone.val($phone.val() + ' '); } if ($phone.val().length === 9) { $phone.val($phone.val() + '-'); } } return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105)); }) .bind('focus click', function () { $phone = $(this); if ($phone.val().length === 0) { $phone.val('('); } else { var val = $phone.val(); $phone.val('').val(val); } }) .blur(function () { $phone = $(this); if ($phone.val() === '(') { $phone.val(''); } }); } else { $('#c_busphone') .keydown(function (e) { if ($(this).val().indexof("+") === -1) { $(this).val("+" + $this.val()); } }) } }); });
not sure if cause error, line needs corrected from
$(this).val("+" + $this.val());
to this
$(this).val("+" + $(this).val());
it fast catch, use browser javascript console debugging.
see updated fiddle here. might want add starting parenthesis international prefix well.
Comments
Post a Comment