Задание
- Создать поле для ввода только цифр.
- Сделать поле, что бы в котором при вводе буквы становились заглавными.
- Написать функция для вывода сообщения при вводе символа в поле (нажатие клавиши)
- Написать функция меняющую цвет поля при установки в нем курсора
Решение
1.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
Введите ваш возраст:
<input type="text">
<script>
document.getElementsByTagName('input')[0].onkeypress = function(e) {
e = e || event;
if (e.ctrlKey || e.altKey || e.metaKey) return;
var chr = getChar(e);
// с null надо осторожно в неравенствах, т.к. например null >= '0' => true!
// на всякий случай лучше вынести проверку chr == null отдельно
if (chr == null) return;
if (chr < '0' || chr > '9') {
return false;
}
}
function getChar(event) {
if (event.which == null) {
if (event.keyCode < 32) return null;
return String.fromCharCode(event.keyCode) // IE
}
if (event.which != 0 && event.charCode != 0) {
if (event.which < 32) return null;
return String.fromCharCode(event.which) // остальные
}
return null; // специальная клавиша
}
</script>
</body>
</html>
2.
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body>
имя: <input type="text" id="fname" onkeyup="myFunction()">
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
3.
<!DOCTYPE html>
<html>
<body>
<input type="text" onkeydown="myFunction()">
<script>
function myFunction() {
alert("функция выполнена");
}
</script>
</body>
</html>
4.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
имя: <input type="text" id="fname" onfocus="myFunction()">
<script>
function myFunction() {
document.getElementById("fname").style.backgroundColor = "red";
}
</script>
</body>
</html>