views:

501

answers:

5

I am trying to set focus to the text box on page load event. I tried many solutions by referring the element id, but couldn't able to focus the element. Later when I inspect the element using firebug I found for the same element the id changes in different execution. I am looking for the simplest solution using javascript or jquery to achieve this

    <h:form id="form"> 
      <rich:dataTable value="#{books}" var="book">
        <ui:repeat value="#{authors}" var="author"> 
          <h:inputText value="#{author.name}"/>
        </ui:repeat>
      </rich:dataTable>
</h:form>
A: 
Private Sub SetFocus(ByVal ctrl As Control)
' Define the JavaScript function for the specified control.
Dim focusScript As String = "<script language='javascript'>" & _
"document.getElementById('" + ctrl.ClientID & _
"').focus();</script>"

' Add the JavaScript code to the page.
Page.RegisterStartupScript("FocusScript", focusScript)
End Sub

hope this will help you..

Sanjay
Is that VB? How does that help?
karim79
+2  A: 
$(document).ready(function(){
  $('input.selected').focus();
});    

should focus the input element with the class 'selected' on page load.

Kind Regards

--Andy

jAndy
Where does the `selected` class come in? Am I just missing it?
patrick dw
not at all, since Kalpana asked for "the" textbox he made no statement that this is the first or the last one in his markup. So, I decided it's probably a good idea to involve a class.
jAndy
+1  A: 

Using jquery, this will grab the first input child of the #form:

$('#form input:eq(0)').focus();
patrick dw
I used like this inside the form, couldn't able to set focus <script type="text/javascript"> jQuery(document).ready(function() { $('#form input:eq(0)').focus(); }); </script>
Kalpana
If you look in Firebug, is the script getting inserted? I assume you have the jQuery framework referenced somewhere. If so, where? It would need to be loaded before you can run any jQuery code.
patrick dw
A: 

According to whatwg.org the HTML5 autofocus attribute is only available in Opera at the moment but will be adopted by other browsers in the future.

<input type="text" autofocus />

<script>
    // jQuery
    $(function(){
        if(!("autofocus" in document.createElement("input"))){
            $("input[autofocus]:eq(0)").focus();
        }
    });
</script>
David Murdoch
+1  A: 

Use

$('#form :input:visible:enabled:first').focus();

during document ready.

BalusC
I used like this. Is this correct? Couldn't able to set focus to an element. <h:form id="form"> <script type="text/javascript"> jQuery(document).ready(function() { $('#form input:first').focus(); }); </script> <rich:dataTable value="#{books}" var="book"> <ui:repeat value="#{authors}" var="author"> <h:inputText value="#{author.name}"/> </ui:repeat> </rich:dataTable></h:form>
Kalpana
Thanks worked like a charm
Phill Pafford