2

I have a login form in struts and I want to have focus on the username field when the page loads.

I am using <html:form> tag and I cannot get this form using its name from javascript as document.formName.username .

How can I do this?

1
  • You should also paste the relevant code, i.e. your form with the textfield on which you're trying to transfer the focus to. Commented Mar 25, 2011 at 12:47

3 Answers 3

1

Assign an id to the input element that you want to focus on, then do:

document.getElementById("myInputId").focus();

Alternately, don't give it an id, and do:

document.getElementsByName("username")[0].focus();

Sign up to request clarification or add additional context in comments.

2 Comments

We cannot assign id to the form like <html:form id="formName"> /so the best way to do this is to access a particular form in a sequence it appears. Same is the ssequence case for form elements. document.forms[0].elements[0]
@imran, no, id is set when you specify a name to your action in struts-config.xml (use <html:html xhtml="true"> if your <html:form> doesn't render an id attribute.
1

We cannot assign id to the form like

/so the best way to do this is to access a particular form in a sequence it appears. Same is the sequence case for form elements.

document.forms[0].elements[0]

Comments

1

if you have <html:form action="/someAction"> and in your struts-config.xml, you've specified a name for that action (which points to an ActionForm) and your html declaration is <html:html xhtml="true"> and inside your form you have <html:input> (with name of "userName"), then you can do this in your javascript:

document.formName.userName.value;

else

document.forms["formName"].userName.value;

2 Comments

We cannot assign id to the form like <html:form id="formName"> /so the best way to do this is to access a particular form in a sequence it appears. Same is the sequence case for form elements. document.forms[0].elements[0]
@imran, no, id is set when you specify a name to your action in struts-config.xml (use <html:html xhtml="true"> if your <html:form> doesn't render an id attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.