How to insert dot instead of comma in js keypress
In my website i have textbox that contains 开发者_开发技巧currency amount separeted by dot. Users sometimes press dot on numpad, and that inserts coma in textbox. How can I convert it to dot ? I was trying to do it in keypress event but didn't menage to make it work.
<input type='text' onkeypress='return check(this,event);'>
function check(Sender,e){
var key = e.which ? e.which : e.keyCode;
if(key == 44){
Sender.value += '.';
return false;
}
}
UPDATE: This should work if you type anywhere in the input box
function check(Sender,e){
var key = e.which ? e.which : event.keyCode;
if(key == 44){
if (document.selection) { //IE
var range = document.selection.createRange();
range.text = '.';
} else if (Sender.selectionStart || Sender.selectionStart == '0') {
var start = Sender.selectionStart;
var end = Sender.selectionEnd;
Sender.value = Sender.value.substring(0, start) + '.' +
Sender.value.substring(end, Sender.value.length);
Sender.selectionStart = start+1;
Sender.selectionEnd = start+1;
} else {
Sender.value += '.';
}
return false;
}
}
If you're looking to transform a comma character as it is typed, I've answered similar questions on Stack Overflow before:
- Can I conditionally change the character entered into an input on keypress?
- show different keyboard character from the typed one in google chrome
However, I agree with @ChrisF's comment above.
You could do:
$('input').keyup(function(e){
var code = e.which ? e.which : e.keyCode;
console.log(code);
if (code === 110){
var input = this.value;
input = input.substr(0, input.length -1);
console.log(input);
input += ',';
this.value = input;
}
});
fiddle http://jsfiddle.net/PzgLA/
精彩评论