Php 如何自动聚焦唯一错误的输入字段?
我有一个FormValidator类,用于验证表单输入 但我现在要检查的是,是否只有一个输入错误。如果有,它应该将Php 如何自动聚焦唯一错误的输入字段?,php,html,forms,validation,error-handling,Php,Html,Forms,Validation,Error Handling,我有一个FormValidator类,用于验证表单输入 但我现在要检查的是,是否只有一个输入错误。如果有,它应该将autofocus属性添加到HTML中输入的中。如果存在超过1个错误,则应保持空字符串变量不变 在我的代码中,我只是将“自动聚焦”添加到每个错误的输入中 有谁能帮我按照我描述的方式得到它 PHP $nameFocus = ''; $emailFocus = ''; $passwordFocus = ''; $validate = new FormValidator()
autofocus
属性添加到HTML中输入的中。如果存在超过1个错误,则应保持空字符串变量不变
在我的代码中,我只是将“自动聚焦”添加到每个错误的输入中
有谁能帮我按照我描述的方式得到它
PHP
$nameFocus = '';
$emailFocus = '';
$passwordFocus = '';
$validate = new FormValidator();
$validation = $validate->check();
if($validation->error('name')) $nameFocus = ' autofocus';
if($validation->error('email')) $emailFocus = ' autofocus';
if($validation->error('password')) $passwordFocus = ' autofocus';
HTML
<form method="post" action="">
<div>
<label>Name</label>
<input type="text" name="name"<?=$nameFocus?>>
</div>
<div>
<label>Email</label>
<input type="text" name="email"<?=$emailFocus?>>
</div>
<div>
<label>Password</label>
<input type="text" name="password"<?=$passwordFocus?>>
</div>
<button>Submit</button>
</form>
名称
>
暗语
.php
:
session_start()
$_SESSION['nameFocus'] = false;
$_SESSION['emailFocus'] = false;
$_SESSION['passwordFocus'] = false;
$validate = new FormValidator();
$validation = $validate->check();
if($validation->error('name')) $_SESSION['nameFocus'] = true;
else if($validation->error('email')) $_SESSION['emailFocus'] = true;
else if($validation->error('password')) $_SESSION['passwordFocus'] = true;
header('Location : ./my_form.php');
.html
:
<?php session_start() ?>
<form method="post" action="">
<div>
<label>Name</label>
<input type="text" name="name" autofocus="<?php echo $_SESSION['nameFocus'] ? 'on' : 'off' ?>">
</div>
<div>
<label>Email</label>
<input type="text" name="email" autofocus="<?php echo $_SESSION['emailFocus'] ? 'on' : 'off' ?>">
</div>
<div>
<label>Password</label>
<input type="text" name="password" autofocus="<?php echo $_SESSION['passwordFocus'] ? 'on' : 'off' ?>">
</div>
<button>Submit</button>
</form>
名称
我看不出这个想法有任何“清晰”之处。您将空变量输入到输入标记中,因此根本不改变它们。实际引入“autofocus”属性的代码在哪里?这正是我正在努力解决的问题。最好先使用客户端验证,这样就可以使用Jquery将autofocus添加到第一个错误字段中,或者您可以使用ajax从服务器返回错误状态,然后使用jquery自动聚焦到有错误的特定字段。谢谢。因为你的回答,我明白了@孩子戴蒙德:很高兴帮助你!)