I’ve created a few input fields, that I am cleaning up as the user types.
So, I’m using a keystroke detection event, like .keyup()
It’s all working very well, but I do notice one thing that’s rather annoying for the users.
While the script is cleaning the data as they type, their cursor is being sent to the end of the input field.
So, if you want to edit the middle of the value, you’re cursor immediately goes to the end of the box.
Does anyone know of a way to maintain the cursor’s current position inside the input field?
I’m not holding my breath, but I thought I’d ask.
Here’s the cleanup code I’m using:
$(".pricing").keyup(function(){
// clean up anything non-numeric
**var itemprice = $("#itemprice").val().replace(/[^0-9\.]+/g, '');**
// return the cleaner value back to the input field
**$("#itemprice").val(itemprice);**
});
If I could make a suggestion, there might be a more elegant solution. Simply disallow non-numeric keys to be entered at all:
**Allow me to revise, this function should work better than the one previously posted:
Of course, you’ll probably want to fine tune a bit but this should get you started.
Also, if you’re concerned about what dclowd9901 said above, you could display a validation message saying that non-numeric entries are not allowed, rather than simply swallowing the keystroke.