I currently use the script below to take any form of information and pull out the numbers to make a phone number with dashes in it. However, if I accidently click in the field, it puts two dashes in there even though nothing was pasted or typed. Does JS have a way to say ONLY if something is pasted then add dashes? The reason it’s a pain is I have 2 search fields, and if I want to use one, the other has to be blank. So if there are 2 dashes in it, I have to delete them out and hit enter in the same field or it will add them again.
I appreciate any help you might have.
<SCRIPT LANGUAGE="JavaScript">
function addDashes(f)
{
f.value = f.value.replace(/\D/g, '');
f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
}
</SCRIPT>
I’m not quite sure if this is what you need, but this just checks to see if there is actually something there before formatting it:
EDIT:
Based on your comment, I thought it might be helpful to bring up validation. I’m not sure if you are doing anything on the server-side to make sure it is a valid phone number, but it might be helpful to do a little validation so taht you don’t add dashes if the user has just typed some spaces.
First, I would remove the non-numeric values before you check the length. I’ve updated the code above to do that.
Next, I would check against some length. Maybe you want to only add dashes if the number is at least 9 digits long. You can decide that length taht you watn to check against. In that case, you would add:
It all depends on if/how you are validating this field.