Home javascript input field for html digits only

input field for html digits only

Author

Date

Category

There is a field & lt; input class = "ss" type = "text" & gt;
I hang an event on it:

$ (". ss"). keyup (function (e) {
 this.value = this.value.replace (/ [^ 0-9 \.] / g, '');
});

As a result, when you enter a letter, it is visible for a moment, and then it is removed. How to make it invisible? Also, “.” it is necessary.


Answer 1, authority 100%

All you need is this:

& lt; input type = "number" & gt; 

Answer 2, authority 60%

You can simply prohibit the entry of unnecessary characters – for example, only numbers and periods:

$ (". ss"). keypress (function (event) {
 event = event || window.event;
 if (event.charCode & amp; & amp; event.charCode! = 0 & amp; & amp; event.charCode! = 46 & amp; & amp; (event.charCode & lt; 48 || event.charCode & gt; 57))
  return false;
}); 
& lt; script src = "https://ajax.googleapis.com/ajax/libs /jquery/1.11.1/jquery.min.js"></script>
& lt; input class = "ss" type = "text" & gt; 

Answer 3, authority 40%

The easiest way to solve this problem is via event ‘input’. It is used purely in (vamilla js). Unfortunately, there is no analogue in jq. Here’s the code to solve this problem.

p.s. I slightly modified the regex

document.querySelector ('. ss'). addEventListener ('input',
  function (e) {
   this.value = this.value.replace (/ [^ \ d.] / g, '');
  }
)

Author of the answer: Hayk Inants, teacher of HackerU


Answer 4, authority 20%

$ ('input'). on ('keydown', function (e) {
 if (e.key.length == 1 & amp; & amp; e.key.match (/ [^ 0-9 '".] /)) {
  return false;
 };
}) 
& lt; script src = "https://ajax.googleapis.com/ajax/libs /jquery/2.1.1/jquery.min.js"></script>
& lt; input / & gt; 

Answer 5, authority 20%

Use not the keyup event, but the input event, and then everything will be good!

$ (". ss"). on ('input', function (e) {
 this.value = this.value.replace (/ [^ 0-9 \.] / g, '');
});

Answer 6

Unfortunately, I can’t write comments, so I’ll write here.
If you are using jquery, why not use a mask on the field?
jQuery Mask


Answer 7

& lt; input class = "ss" type = "text" onkeypress = "banText () & gt;
& lt; script & gt;
function banText () {
  let banText = parseFloat (event.key);
  if (isNaN (banText)) {
    event.preventDefault ();
  } else {
    console.log (banText);
  }
& lt; / script & gt;

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions