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.
2
Answers
You can also try jQuery based method:
You can set require attribute simply adding
required
in your input tags.And also set focuse on first
input
tag by addingautofocus
attribute in your input tag.Note: The
autofocus
attribute cannot be used on inputs of typehidden
, since hidden inputs cannot be focused.