Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contenteditable allow numbers only for editing?

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!

like image 885
Ong Kong Tat Avatar asked Jul 13 '17 06:07

Ong Kong Tat


People also ask

How do you make a P tag editable?

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.

How do I make a div not editable?

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);

What is false about Contenteditable attribute?

contenteditable="false" Indicates that the element is not editable. contenteditable="inherit" Indicates that the element is editable if its immediate parent element is editable.

How do I stop Enter key in Contenteditable?

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.


2 Answers

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();
    });
like image 184
Sumit Kumar Gupta Avatar answered Oct 21 '22 11:10

Sumit Kumar Gupta


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

like image 39
Ali Jamal Avatar answered Oct 21 '22 11:10

Ali Jamal