Home > Blockchain >  Use Jquery to add commas to text input and prefix £
Use Jquery to add commas to text input and prefix £

Time:08-27

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!

CodePudding user response:

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="£" />

CodePudding user response:

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="£" />

  • Related