I have login/register forms that have several input
tags in it.
I would like to set focus and require attribute on first input
tag when I open this form.
I tried jQuery and JavaScript code and it works fine on require attribute.
When input
tag's values are empty, it says warning alert but setting focus doesn't work.
Below is my code.
<form className="Form_login">
<h2>Login</h2>
{location.state?.message &&
(<div className="Message_login">
{location.state?.message}
</div>)}
{error && <div className="Alert_login">{error}</div>}
<label className="InputGroup_login" htmlFor="email">
Email:
<input className="Input_login"
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</label>
<label className="InputGroup_login" htmlFor="password">
Password:
<input className="Input_login"
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</label>
<div className="ButtonContainer_login">
<button className="Button_addhome Input_addhome"
onClick={handleSubmit}>Login</button>
<Link to = "/"
className="Button_link Input_addhome"
style={{textAlign:"center"}}>Cancel</Link>
</div>
<div style={{ textAlign: "center", paddingTop: "1rem" }}>
<span>
forgot password or <Link to="/register">register</Link>
</span>
</div>
</form>
Please help me.
You can also try jQuery based method:
$(document).ready(function() {
$('form:first *:input[type!=hidden]:first').focus();
});
You can set require attribute simply adding required
in your input tags. And also set focuse on first input
tag by adding autofocus
attribute in your input tag.
<input className="Input_login
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
autofocus
/>
Note: The autofocus
attribute cannot be used on inputs of type hidden
, since hidden inputs cannot be focused.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.