Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
Use Jquery to add commas to text input and prefix £

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can add the symbol £ in the beginning of return:

// 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, ",");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
<input id="income" type="text" value="£" />

about 4 years ago · Juan Pablo Isaza Report

0

This can be done using one event keydown or keyup. For demonstration I've used keyup event.

$('#income').keyup(function(event) {

    // skip for arrow keys
    if(event.which >= 37 && event.which <= 40) return;

    let val = $(this).val(); 
    val = format_number(val);
    val = prefix_currency(val);
    
    $(this).val(val);
});

function prefix_currency(val, cur = '£' ) {
    if(val.indexOf(cur) !== 0) {
        val = cur + val;
    }
  
    return val;
}

function format_number(val) {
    return val
        .replace(/\D/g, "")
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="income" type="text" value="£" />

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!