I’m looking for a way to prefix a £
in an input text field but also add commas for number formatting. I’ve got working functions for both but together they alter each other and don’t work.
Working code to prefix £
:
$("#income").keydown(function(e) {
var oldvalue=$(this).val();
var field=this;
setTimeout(function () {
if(field.value.indexOf('£') !== 0) {
$(field).val(oldvalue);
}
}, 1);
});
Working code for commas:
// Add comma to input field
$('#income').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value.replace(/D/g, "")
.replace(/B(?=(d{3})+(?!d))/g, ",");
});
});
jsfiddle: http://jsfiddle.net/c40bvpo1/1/
Many thanks!
2
Answers
You can add the symbol
£
in the beginning ofreturn
:This can be done using one event
keydown
orkeyup
. For demonstration I’ve usedkeyup
event.