Alex Rivera | Logout

how to set focus to first editable input element in form

Asked 2011-11-05T21:44:27.043
13

Dynamically created form contains input elements. First elements may be disabled or readonly. I tired code below to set focus to first elemnt which accepts data to enable fast data enttry form keyboard. However if form fist element is disable or readonly, focus is not set. How to set focus to first element which accepts data ?

    <form style='margin: 30px' id="Form" class='form-fields' method='post' target='_blank'
    action='Report/Render'>
...
    <input id='_submit' type='submit' value='Show report' class='button blue bigrounded' />
    </form>
    <script type="text/javascript">
        $(function () {
            var elements = $('#Form').find(':text,:radio,:checkbox,select,textarea');
            elements[0].focus();
            elements[0].select();
});
</script>

Update

There are also hidden input fields, sorry. Answers provided set focus to hidden element. Answr containing function does not find any element.ˇ

Here is the update testcase:

$(function () {
  $("#form :input:not([readonly='readonly']):not([disabled='disabled'])").first() 
                                                                        .focus(); 
});

How to set focus to vist visible, enabled and not readonly element ?

Update 3

I tried Row W code where input element was added. Now it sets focus to second element. Testcase is shown at Revision 5 of Rob W's answer

Edit
Report

1 Answer

4

Use jQuery's :not() selector:

$("#myForm :input:not([readonly='readonly']):not([disabled='disabled']):reallyvisible").first()
                                                                                      .focus();

Here's a working fiddle.

EDIT:

To meet the new requirement you posted in the comments, you'll have to extend the :visible selector to check for parent visibility (untested):

jQuery.extend(
  jQuery.expr[ ":" ], 
  { reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
);
answered 2011-11-05T21:46:53.383

Your Answer