skip to Main Content

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


  1. You can also try jQuery based method:

    $(document).ready(function() {
        $('form:first *:input[type!=hidden]:first').focus();
    });
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search