Stack Exchange
javascript input format while typing doesn't work
I need help. I have a input box and I need to build specific format while typing.
I need 121.22’37” W
Here is my code


function formatField(f) {
  f = f.replace(/[^0-9A-Za-z]/g, "")
  var n = f
  if (f.length >= 3) n = f.substr(0, 3) + "." + f.substr(3, 3)
  if (f.length >= 5) n += "’" + f.substr(5, 5)
  if (f.length >= 7) n += "”" + f.substr(7, 1)
  if (f.length >= 9) n += "W"
  return n
}
<input class="mrcinput" ${disabled( 'LATITUDE')} id="LATITUDE" maxlength="10" name="LATITUDE" onkeyup="this.value=formatField(this.value);" size="25" title="Latitude" type="text" />




Hi! Can you share what's not working (e.g. not updating? or updating wrong? or?) in your code too?

it formats properly up to 121.22' and after that doesn't format right. Also I need to make sure that if at the begining a space function allow to enter it.

so it can be 121.22’37” W  or  21.22’37” W

Probably need to escape the single quote before you process the string eg f = f.replace(/'/g, "\\\'")

You have a mess in a logic. 
The fixed code is below. However, this is not really a good approach, since it is hard to edit, so you'll need to handle backspace separately. 


function formatField(source) {
  var n = '';
  f = source.replace(/[^0-9A-Za-z]/g, "")
  if (source[0] === ' ') f = ' ' + f;
  var n = f;

  if (f.length >= 3) n = f.substr(0, 3) + "." + f.substr(3, 2)
  if (f.length >= 5) n += "’" + f.substr(5, 2)
  if (f.length >= 7) n += "”"
  if (f.length >= 8) n += " W"
  return n
}
<input class="mrcinput" ${disabled( 'LATITUDE')} id="LATITUDE" maxlength="11" name="LATITUDE" onkeyup="this.value=formatField(this.value);" size="25" title="Latitude" type="text" />




Thanks a lot. This is exactly what I needed.

@Dima consider upvoting and marking as accepted is the answer helped you to close the question.

When working with strings on the front-end, be aware of where you want to use it and what can cause your code to halt. 
Do you need the string in javascript? Pay attention to the single ( ' ) and double quotes ( " ) and ensure you escape it with a backslash (\). 
Do you need it in an HTML element? You probably need to convert it to (&#39;) and (&quot;) respectively just so these special characters don't accidentally cut your markup short.
