Contenteditable allow numbers only for editing?
Why not just use an input?
<input type="number">
If you still want to use contenteditable, you can add an event listener like so:
$("#myeditablediv").keypress(function(e) {
if (isNaN(String.fromCharCode(e.which))) e.preventDefault();
});
This will block all characters that are not numbers (0-9)
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();
});