views:

223

answers:

3

hi i'm using struts (form) + validation i just want to ask if can i set focus on some field on form after validation without javascript? i think i red something in book programming jakarta struts but i can't remember.

thanks

A: 

You can set the tabindex="1" attribute of the input which you want to have obtain the focus first, when the page reloads.

Bozho
+1  A: 

You cannot set focus on a certain field with pure HTML. The tabindex idea as suggested by Bozho is nice, but it will only work if you actually press tab for the first time. It has however the disadvantage that it changes the tabbing order of the input elements. Not really user friendly.

You'll really need to grab JavaScript for this. Just do something like:

window.onload = function() {
   document.formname.${inputname}.focus();
   // or:
   document.getElementById(${inputid}).focus();
};

...where ${inputname} dynamically resolves to name of the input field as in <input name="foo"> and where ${inputid} resolves to ID of input field as in <input id="foo">. That's all.

BalusC
he said "wihtout js", that's why I gave the only option I could think of (has its drawbacks). btw, the focus is set even without pressing tab.
Bozho
@Bozho: Sorry, in a basic testcase the field didn't get immediate focus after page load in any of the 5 major webbrowsers I've here.
BalusC
ah, ok. I was looking at a site with set tabindex, but then it appeared to have a 'hidden' js as well.
Bozho
A: 

You can't set the focus on a field without using JavaScript. Others have tried and failed (CSS was the first place they looked at, but that doesn't cut it either).

Not sure what you've read in the book Jakarta Struts, but maybe you are referring to the focus attribute of the Struts <html:form> tag? That sets the focus on the desired form field without you needing to add JavaScript. But Struts will add the JavaScript, so that means no JavaScript from your side, and not no JavaScript at all.

dpb