Сообщение от Espidsdfeer
|
Главное условие - чтобы поле не было пустым.
|
Ну если только это, тогда так
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
<style>
form label{
display: inline-block;
width: 100px;
}
form div{
margin-bottom: 10px;
}
.error{
color: red;
margin-left: 5px;
}
.success{
color:green;
margin-left: 5px;
}
label.error{
display:inline;
}
</style>
</head>
<body>
<h2>Form 1</h2>
<form id="first_form" method="post" action="" novalidate>
<div>
<label>Name</label>
<input type="text" class = "first_name" name="first_name" required></input>
</div>
<div>
<label>Last Name</label>
<input type="text" class = "last_name" name="last_name" required></input>
</div>
<div>
<label>E-Mail</label>
<input type="text" class = "email" name="email" required></input>
</div>
<div>
<label>Password</label>
<input type="password" class = "password" name="password" required></input>
</div>
<div>
<input type="submit" value="Submit Form 1">
</div>
</form>
<h2>Form 2</h2>
<form id="form2" method="post" action="" novalidate>
<div>
<label>Age</label>
<input type="text" class = "age" name="age" required></input>
</div>
<div>
<label>Film Genre</label>
<input type="text" class = "genre" name="genre" required></input>
</div>
<div>
<label>Music</label>
<input type="text" class = "music" name="music" required></input>
</div>
<div>
<label>Another field</label>
<input type="password" class = "field" name="field" required></input>
</div>
<div>
<input type="submit" value="Submit Form 2" onclick="return submit">
</div>
</form>
<script>
function CheckForm (ev) {
const valid = ev.target.querySelectorAll('input:not([type=submit]):valid')
valid.forEach (inp => {
inp.style.borderColor = 'green';
inp.insertAdjacentHTML('afterend', '<span class="success">Поле заполнено</span>')
})
const invalid = ev.target.querySelectorAll('input:invalid')
if (!invalid.length) {
setTimeout(() =>alert('Успешная отправка формы!'),0)
return
}
invalid.forEach (inp => {
inp.style.borderColor = 'red';
inp.insertAdjacentHTML('afterend', '<span class="error">Поле не заполнено</span>')
})
setTimeout(() =>alert("Не все поля заполнены! Форма не отправлена"), 0)
ev.preventDefault()
}
document.querySelector('#first_form').addEventListener('submit',CheckForm)
document.querySelector('#form2').addEventListener('submit',CheckForm)
</script>
</body>
</html>