There is a code, it does not allow the input of any characters, except natural numbers.

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript"> function check_field(id) { var field = document.getElementById(id); if (isNaN(field.value)) { alert('Помилка! Не дійсне число') } } </script> </head> <body> <form> Введіть дійсне число: <input type="text" id="t_field" onkeyup="this.value = this.value.replace(/\.(?=.*\.)|[^\d\.eE-]/g, '');"> <input type="button" value="Перевірити" onclick="check_field('t_field');"/> </form> </body> </html> 

I want to know how this line works, borrowed from another code.

 <input type="text" id="t_field" onkeyup="this.value = this.value.replace(/\.(?=.*\.)|[^\d\.eE-]/g, '');"> 
  • Um ... When you enter the next character cuts out all the characters that are not part of the number? - user207618

2 answers 2

The onkeyup event occurs when you release the key. see http://htmlbook.ru/html/attr/onkeyup

  1. Inside, you can specify both the function and the js itself.
  2. this is the current js object to access the input field.
  3. this.value - user entered value
  4. this.value.replace - search and replace in the meaning of anything. see https://javascript.ru/string/replace

In this situation, everything that falls under the regular expression \.(?=.*\.)|[^\d\.eE-] will be replaced with an empty string (that is, deleted) after user input

    The regular expression (/\.(?=.*\.)|[^\d\.eE-]/g cuts off all the characters that are not part of the specified number. Read about regular expressions and expand the possibilities of input.