How to partial complete text input
I know the title doesn't capture what I'm trying to ask but here is what I'm trying to do:
// desired format is: 123-123-1234
When the user enters 123 (the first three characters) how can I append the hyphen - Then when the user enters 123 (the second three characters) how can I append the hyphen - again And then allow the user only to ente开发者_Go百科r the last four numbers?
I have a function that validates the US Phone number format I want:
/* US Phone # */
'us_phonenumber':function($fld) {
var v = $fld.val();
if(v.length == 0) {
return true;
}
return /^\d{3}-\d{3}-\d{4}$/.test(v);
},
Just curious if I could add some sort of partial auto complete method while still validating
HTML:
<input type="text" />
<br /><a href="#" id="check">Click me!</a>
JS:
$("#check").click(function(){
var pNum = $("input").val();
var vNum = pNum.slice(0, 3)+"-"+pNum.slice(3, 6)+"-"+pNum.slice(6, 10);
$("input").val(vNum);
return false;
});
Fiddle: http://jsfiddle.net/ueyhE/
Type in your number, then press "Click me!".
EDIT:
Using change()
:
$("input").click(function(){
var pNum = $(this).val();
var vNum = pNum.slice(0, 3)+"-"+pNum.slice(3, 6)+"-"+pNum.slice(6, 10);
$(this).val(vNum);
});
i don't know about doing during input, but after the input is complete might be less confusing for the user, or less margin for error.
var string = '1234567890';
var formattedString = '';
var index;
for (var i = 0; i < string.length; i++) {
index = string.charAt(i);
(i == 3 || i == 6) ? formattedString = formattedString + '-' + index : formattedString = formattedString + index;
}
alert(formattedString);
精彩评论