I am trying to do a value replace in an input field. It is almost working correctly. The problem is it adds the value to the end of input when I only want it added to the one location
Html:
<input id="boom" value="03/15/0212" />
Jquery: I have hard coded some values to keep from placing all functions
$('#boom').on('keypress', function (e)
{
var crs = this.selectionStart;
var from;
var to;
var sub;
_dateSection = 'month';
var currentObj = this;
var currentVal = $(this).val();
var c = String.fromCharCode(e.which);
var stringSplit = currentVal.split('/');
switch (_dateSection) {
case 'month':
_currentDateValue = stringSplit[0];
from = 0;
to = 2;
sub = currentVal.substring(from, to);
break;
case 'day':
_currentDateValue = stringSplit[1];
from = 3;
to = 6;
sub = currentVal.substring(from, to);
break;
case 'year':
_currentDateValue = stringSplit[2];
from = 6;
to = 10;
sub = currentVal.substring(from, to);
break;
};
var check = false;
if (!check) {
$(currentObj).val(function (index, value)
{
return value.replace(sub, c);
});
}
});
If you add 3 to the month portion of the input which is currently populated with 03 it replaces is correctly with 3, but it also adds 3 to the end of the year. Making the year, 20123 when the year value should remain 2012.
The final value should be
3/15/2012
not
3/15/20123
Edit:
this code gives the same problem:
$(currentObj).val(currentVal.replace(sub, c));
as does this
var replaceValue = currentVal.replace(sub, c)
$(currentObj).val(replaceValue);
The extra character that is added to the end is added by the input field itself. The keypress event is handled by the input also, which does the normal thing and adds the character to the value.
Just put
e.preventDefault();in your event handler to keep the input from getting the event.Also, don’t use
replaceto put the character in the string, usesubstrto get the parts of the string that you want to keep:If the string is for example
05/05/2012and you try to replace the day with4, it will instead replace the first occurace and you get4/05/2012instead of05/4/2012.