ramin
ramin

Reputation: 480

Add Commas for numbers in content editable DIV when key up

sorry, my English is not good.

i want add commas for number when keyUp function. in content editable DIV.

My code is currently working in reverse.

function addCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
$('div').keyup(function (){
  var currentInput = $(this).text();
  var fixedInput = currentInput.replace(/[A-Za-z!@#$%^&*()]/g, '');
  $(this).text(fixedInput);
  var test = /\D/;
  if (test.test($(this).text())) {
    $(this).text($(this).text().replace(/\D/g, ""));
  }
  $(this).text(addCommas($(this).text()));
})
div{
background-color:#ccc;
padding:5px;
border:1px dashed #000;
width:20%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable="true">
0
</div>

Upvotes: 0

Views: 157

Answers (1)

Heemanshu Bhalla
Heemanshu Bhalla

Reputation: 3765

Main problem here is when you replace element's value using $(this).text() on Keyup event cursor frequently reset its positions as you are pressing keys one after the other. It eventually sets it to start position in your case.

In order to fix it, we need to initially save text position inside input under keyup event when its fired or key is pressed. then we need to set it again when code under keyup event has done its processing.

third thing is to use this.value instead of text() to replace processed text of input. it set the updated value instead of replacing the text.

Fixed Code Below with Running Snippet

function addCommas(x) {
    alert(x);
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}
$('div').keyup(function() {
    var position = this.selectionStart;
    var currentInput = $(this).text();
    var fixedInput = currentInput.replace(/[A-Za-z!@#$%^&*()]/g, '');
    this.value = fixedInput;

    //$(this).text(fixedInput);
    var test = /\D/;
    if (test.test($(this).text())) {
        //$(this).text($(this).text().replace(/\D/g, ""));
        this.value = this.value.replace(/\D/g, "");

    }
    //$(this).text(addCommas($(this).text()));
    this.value = this.value;
    this.selectionEnd = position;

})
div{
    background-color:#ccc;
    padding:5px;
    border:1px dashed #000;
    width:20%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable="true">
0
</div>

Upvotes: 1

Related Questions