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!
You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.
Try something like this: // Disable all input-like elements in the divs except for the last div $(". divclass:not(:last-child) :input"). attr("disabled", true);
contenteditable="false" Indicates that the element is not editable. contenteditable="inherit" Indicates that the element is editable if its immediate parent element is editable.
To prevent contenteditable element from adding div on pressing enter with Chrome and JavaScript, we can listen for the keydown event on the contenteditable element and prevent the default behavior when Enter is pressed. to add a contenteditable div. document. addEventListener("keydown", (event) => { if (event.
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();
});
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
Let me know if you face any bug in comments
Thank you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With