only allow numbers in contenteditable elements?

Viewed 16740

How can I make contenteditable elements only allow entry of numeric values?

I tried to use something like:

onkeypress='return event.charCode >= 48 && event.charCode <= 57'

...on elements that are contenteditable, but it still allows entry of alphabetic characters.

Thanks!

4 Answers

Salaam

This will allow only numbers

$('[contenteditable="true"]').keypress(function(e) {
    var x = event.charCode || event.keyCode;
    if (isNaN(String.fromCharCode(e.which)) && x!=46 || x===32 || x===13 || (x===46 && event.currentTarget.innerText.includes('.'))) e.preventDefault();
});

I have also tested decimals. There are three major conditions to get allowed

  • Is a Number and Not delete button
  • Not Space
  • Not Enter Button
  • Allow Decimal point only once

Let me know if you face any bug in comments

Thank you

If you want to enter only 0-9 in contenteditable div then you can use this code. This code also prevent user to copy paste into the field

<div contenteditable id="myeditablediv"  oncopy="return false" oncut="return false" onpaste="return false">10</div>

Javascript

$("#myeditablediv").keypress(function(e) {
        if (isNaN(String.fromCharCode(e.which))) e.preventDefault();
    });

if you want to enter decimal points instead of a number then you can use this javascript code

 $("#myeditablediv").keypress(function(e) {
        var x = event.charCode || event.keyCode;
        if (isNaN(String.fromCharCode(e.which)) && x!=46) e.preventDefault();
    });

If you want to allow only numbers, you can use :

if (e.which < 48 || e.which > 57) e.preventDefault();

If you want to enable pad numbers, use this code :

if (!e.key.match(/^[0-9]/g) && e.keyCode !== 8 && e.keyCode !== 46) {
    e.preventDefault();
}

The regex starts with '^' to prevent F5 to works for example. We add e.keycode 8 and 46 to avoid the prevent default on backspace/delete

This method doesn't allow decimals, you'll need to modify regex for it

Related